watchOS: Complications

Feb 7 2023 · Swift 5.6, watchOS 8.5, Xcode 13

Part 2: Tinted & Custom Complications

12. Refactor SwiftUI Views

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 11. Build a SwiftUI View for a Complication Next episode: 13. Display a SwiftUI View in a Complication

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Right now, the code for our event view has multiple issues. Not only are you unable to preview the complication, but everything is tied to EventKit.

Creating an Event type

We’ll want both SwiftUI and EventKit for this type, and we’ll make it struct called “Event”

import EventKit
import SwiftUI

struct Event {

}
struct Event {
  let color: Color
  let startDate: Date
  let endDate: Date
  let title: String
  let location: String?
  init(ekEvent: EKEvent) {
    color = Color(ekEvent.calendar.cgColor)
    startDate = ekEvent.startDate
    endDate = ekEvent.endDate
    title = ekEvent.title
    location = ekEvent.location
  }
extension Event {
// Move init(ekevent:) here
}

Refactoring the view

OK, let’s take another look at EventView.swift

let event: Event
static var event = Event(
  color: .blue,
  startDate: .now,
  endDate: .now.addingTimeInterval(3600),
  title: "Gnomes rule!",
  location: "Everywhere"
)
EventView(event: event)
import ClockKit
  CLKComplicationTemplateGraphicRectangularFullView(
    EventView(event: event)
  )
    .previewContext()
let event: Event?
} else if let event = event {
  EventView(event: event)
EventComplicationView(event: nil)
EventComplicationView(event: nil)