Accessing system colors in WatchKit

Viewed 615

I am trying to use UIKit colors for my Apple Watch interface. You can do it in iOS with UIColor class properties like .systemBackground and others. For example:

let myColor = UIColor.systemBlue

Gives me error when compiling watchOS extension target:

Type 'UIColor' has no member 'UIColor.systemBlue'.

I wonder tis there alternative way to get this system colors, and if not — what I need is to get a color of some UI elements, like SwiftUI table view row background which looks very similar to UIColor.systemGray5.

@State private var isActive = false

var body: some View {
  List {
    Section() {
      ForEach(self.dataSource) { item in
        CustomCell()
        .listRowPlatterColor(self.isActive ? Color(UIColor.systemGray5) : Color(.orange))
      }
    }
  }
}

Code above won't compile because UIColor.systemGray5 is not found in WatchKit. I have tried to create a class which is sued both in iPhone and Watch target and it fixes Xcode autocompletion. But the app breaks when trying to use it the Apple Watch target.

I hope there's a way rather then finding correct color and hard-coding it.

2 Answers

Looking at the documentation, the UIColor.system-ish are only available for iOS, Catalyst and some for tvOS. What you can do is extend UIColor and create you systemGray5:

extension UIColor {
    static var mySystemGray5: UIColor {
        return .init(red: 229/255, green: 229/255, blue: 234/255, alpha: 1)
    }
}

And use on your code like:

  ForEach(self.dataSource) { item in
    CustomCell()
    .listRowPlatterColor(self.isActive ? Color(UIColor.mySystemGray5) : Color(.orange))
  }

Since you are using SwiftUI, Color.blue is equivalent to UIColor.systemBlue.

Unfortunately, Color doesn't have a lots of UIColor system colors, hopefully Apple add missing colors on WWDC 2020.

May be use can use something like Color.gray.opacity.opacity(0.25) in the meanwhile?

Related