Swift, SwiftUI - .getRed(& red, green: & green, blue: & blue, alpha: & alpha)

Swift, SwiftUI - .getRed(&red, green: &green, blue: &blue, alpha: &alpha)

我正在关注 iOS 在线课程的斯坦福大学 CS193p 开发应用程序。

我正在尝试 Assignment 6 Memorize.pdf

它说使用下面的代码⬇️,但它总是给我白色。某处有错误吗?请帮忙。

import SwiftUI

struct RGBAColor: Codable, Equatable, Hashable {
    let red: Double
    let green: Double
    let blue: Double
    let alpha: Double
}

extension Color {
    init(rgbaColor rgba: RGBAColor) {
        self.init(.sRGB, red: rgba.red, green: rgba.green, blue: rgba.blue, opacity: rgba.alpha)
    }
}

extension RGBAColor {
    init(color: Color) {
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0
        if let cgColor = color.cgColor {
            UIColor(cgColor: cgColor).getRed(&red, green: &green, blue: &blue, alpha: &alpha)
        }
        self.init(red: Double(red), green: Double(green), blue: Double(blue), alpha: Double(alpha))
    }
}
import SwiftUI

struct ContentView: View {
    static let rgbaColorRed = RGBAColor(color: Color.red)
    static let thisShouldBeRed = Color(rgbaColor: rgbaColorRed)
    
    var body: some View {
        Text("Hello, world!")
            .padding()
            .foregroundColor(ContentView.thisShouldBeRed) // why white here, not red???
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

正如 cgColor 属性 的文档所说:

For a dynamic color, like one you load from an Asset Catalog using init(_:bundle:), or one you create from a dynamic UIKit or AppKit color, this property is nil.

Color.red实际上是动态颜色:

A context-dependent red color suitable for use in UI elements.

因此 Color.red.cgColor 为零,导致 getRed(_:green:blue:alpha:) 调用不是 运行,并且 redgreenbluealpha局部变量保持0。所以你得到的颜色不是“白色”,而是“透明”。

您实际上可以直接从 Color 创建一个 UIColor,而无需经过 CGColor:

var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0

// note here:
UIColor(color).getRed(&red, green: &green, blue: &blue, alpha: &alpha)
self.init(red: Double(red), green: Double(green), blue: Double(blue), alpha: Double(alpha))