New in SwiftUI 3: TimelineView in SwiftUI 3 and iOS 15

DevTechie
DevTechie
Published in
5 min readOct 1, 2021

--

TimelineView is another addition to iOS 15 and gives us a view that update its content periodically with the schedule provided by you.

Timeline view itself doesn’t have any appearance but it acts like a container (just like Group). Its main responsibility is to redraw its content at scheduled points in time.

Let’s start with init for TimeLineView:

public init(_ schedule: Schedule, @ViewBuilder content: @escaping (TimelineView<Schedule, Content>.Context) -> Content)

We have two parameters for init so let’s take a look at them first:

schedule: this is a type that conforms to TimelineSchedule protocol and will determine when to update the content.

content: this is a ViewBuilder type closure that returns a view that will be updated based on the schedule. This closure also provides access to Context object which gives us access to date (the date when update occurred) and cadence (the rate at which the timeline updates the view).

Let’s start with a simple digital clock example as shown in the code below

struct SimpleTimeLineViewExample: View {
private var dateFormatter: DateFormatter {
let dt = DateFormatter()
dt.dateStyle = .none
dt.timeStyle = .medium
return dt
}

var body: some View {
ZStack {
Capsule()
.fill(.blue.opacity(0.2))
.frame(maxHeight: 100)

TimelineView(.periodic(from: Date(), by: 1)) { context in
Text(dateFormatter.string(from: context.date))
.font(.title)
}

}
}
}

Output:

Let’s update our code to add some flare✨

struct SimpleTimeLineViewExample: View {
private var dateFormatter: DateFormatter {
let dt = DateFormatter()
dt.dateStyle = .none
dt.timeStyle = .medium
return dt
}

var body: some View {
ZStack {
Capsule()
.fill(.blue.opacity(0.2))
.frame(maxHeight: 100)

TimelineView(.periodic(from: Date(), by: 1)) { context in
let color = Color(red

--

--

DevTechie
DevTechie