somewhat crude, but working well for me. The approach is
to put a transparent TextField
on top of a Text
that does all the attributed string functions.
You will have to adjust the code for multilines etc...
struct ContentView: View {
@State var txt = "A99"
var body: some View {
ZStack (alignment: .leading) {
Text(txt) { str in
var temp: AttributedString = ""
for char in txt {
var charx = AttributedString(String(char))
charx.foregroundColor = char.isLetter ? .red : .black
temp.append(charx)
}
str = temp
}
TextField("", text: $txt).foregroundColor(.clear)
}.frame(width: 222, height: 33).border(.green)
}
}
EDIT1: include the required Text extension from:
How to use Attributed String in SwiftUI
extension Text {
init(_ string: String, configure: ((inout AttributedString) -> Void)) {
var attributedString = AttributedString(string) /// create an `AttributedString`
configure(&attributedString) /// configure using the closure
self.init(attributedString) /// initialize a `Text`
}
}