0

I have this code:

// 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)

What must I do to get the red, green and blue component from the string as parameters for the Color()? So, how to get the substrings?

I tried the extension from here: How does String substring work in Swift

but it gives me: Cannot use instance member '$activeWindowBorderColorText' within property initializer; property initializers run before 'self' is available

24unix
  • 11
  • 1
  • 5
  • You can move your code to `.onAppear(perform:)` and you will be able to access `activeWindowBorderColorText` (without the `$` or `_`). Alternatively, move the `UserDefaults.standard ...` code inside the initializer and use the value directly. – George Nov 19 '20 at 16:39

2 Answers2

0

How about computed properties?

var red: String { activeWindowBorderColorText[1..<2] }

They update with the state.

Kai Zheng
  • 6,640
  • 7
  • 43
  • 66
0

Thank you both for the reply, I got it to work with a combination of .onAppear() and computed properties.

The conversion looks ugly, but it works :-)

.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)

}

24unix
  • 11
  • 1
  • 5