首页 > 解决方案 > SwiftUI 初始化视图的值

问题描述

我有这个代码:

// Border Color
@State private var activeWindowBorderColorText: String = UserDefaults.standard.string(forKey: "ActiveWindowBorderColor") ?? "775759"
let red = $activeWindowBorderColorText[1..<2]
@State private var activeWindowBorderColor = Color(.sRGB, red: red, green: 1, blue: 1)

我必须怎么做才能从字符串中获取红色、绿色和蓝色分量作为 Color() 的参数?那么,如何获取子字符串呢?

我从这里尝试了扩展: String substring 如何在 Swift 中工作

但它给了我:不能在属性初始化程序中使用实例成员'$activeWindowBorderColorText';属性初始化程序在“自我”可用之前运行

标签: viewswiftuiinitialization

解决方案


谢谢你们的回复,我让它结合使用 .onAppear() 和计算属性。

转换看起来很难看,但它有效:-)

.onAppear() {
print("initial color: \(activeWindowBorderColorText)")
var redHex: String { activeWindowBorderColorText[4..<6] }
let redDec = Int(redHex, radix:16)
let red = Double(redDec ?? 1)
var greenHex: String { activeWindowBorderColorText[6..<8] }
let greenDec = Int(greenHex, radix:16)
let green = Double(greenDec ?? 1)
var blueHex: String { activeWindowBorderColorText[8..<10] }
let blueDec = Int(blueHex, radix:16)
let blue = Double(blueDec ?? 1)
print("color: \(activeWindowBorderColorText) redHex: \(redHex ) redDec: \(redDec ?? 1) red:\(red)")
print("color: \(activeWindowBorderColorText) greenHex: \(redHex ) greenDec: \(redDec ?? 1) green:\(green)")
print("color: \(activeWindowBorderColorText) blueHex: \(redHex ) blueDec: \(redDec ?? 1) blue:\(blue)")
activeWindowBorderColor = Color(.sRGB, red: red, green: green, blue: blue)

}


推荐阅读