How can I change a SwiftUI Color to UIColor?

后端 未结 5 957
醉酒成梦
醉酒成梦 2021-01-07 17:02

I\'m trying to change a SwiftUI Color to an instance of UIColor.

I can easily get the RGBA from the UIColor, but I don\'t know how to get the "Color" instan

5条回答
  •  悲&欢浪女
    2021-01-07 17:13

    This is not how SwiftUI works. What you are trying to do is very UIKit like. In SwiftUI you rarely interrogate a view for any parameter. At this time, Color does not have any method or properties that return its RGB values. And I doubt there will ever be.

    In general, with SwiftUI you need to go to the source, that is, the variable you used to create the color in the first place. For example:

      let r = 0.9
      let g = 0.4
      let b = 0.7
      let mycolor = Color(red: r, green: g, b, opacity: o)
    

    There is nothing like this:

    let green = mycolor.greenComponent()
    

    Instead, you need to check variable g (the variable you used to create the color):

    let green = g
    

    I know it sounds odd, but that's how the framework has been designed. It may take time to get use to it, but you eventually will.

    You may ask, but what if mycolor was created as:

    let mycolor = Color.red
    

    In that particular case, you are out of luck :-(

提交回复
热议问题