view - 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';属性初始化程序在“自我”可用之前运行
解决方案
谢谢你们的回复,我让它结合使用 .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)
}
推荐阅读
- centos7 - 主/备份无法正常运行,Keepalived
- javascript - 我无法将护照 js 与 sequelize 一起使用,
- node.js - 如何在Sinon中使用多个参数存根猫鼬方法?
- vb.net - 初始化字体的最佳事件
- python - 如何使用 QWebEngine 在同一窗口中打开任何链接(_blank)
- kubernetes - 在 Kubernetes 中校准应用程序
- c# - 如何使用 sqlite 数据库上传和检索图像
- android - 安全异常:尝试通过 appium 检查器打开 Facebook 应用程序时拒绝权限
- c# - 如何 C# 调整图片大小 Docx
- twitter - 在 .NET Core 2.2 中处理 Twitter API 以验证访问令牌