Posts

Post not yet marked as solved
5 Replies
I missed required property. var hexColor: UInt
Post not yet marked as solved
5 Replies
I made .transformable work this way, but there is - probably/hopefully - better solution as this looks ugly. import SwiftUI import SwiftData @Model final class MyModel { // ... @Attribute(.transformable) var color: Color { get { _$observationRegistrar.access(self, keyPath: \.hexColor) return Color(hex: self.getValue(for: \.hexColor)) } set { _$observationRegistrar.withMutation(of: self, keyPath: \.hexColor) { self.setValue(for: \.hexColor, to: newValue.hex) } } } // ... } And here is the extension. import SwiftData import SwiftUI import UIKit extension Color { var hex: UInt { let components = self.cgColor?.components let r = components?[0] ?? 0 let g = components?[1] ?? 0 let b = components?[2] ?? 0 let red = UInt(r * 255) << 16 let green = UInt(g * 255) << 08 let blue = UInt(b * 255) return red | green | blue } init(hex: UInt, alpha: Double = 1) { self.init( .sRGB, red: Double((hex >> 16) & 0xff) / 255, green: Double((hex >> 08) & 0xff) / 255, blue: Double((hex >> 00) & 0xff) / 255, opacity: alpha ) } }