Reputation: 163
I'm trying to change the color of the caret in a SwiftUI textfield.
I tried:
.accentColor(Color.init(red: 0.34, green: 0.31, blue: 0.23, opacity: 1.00))
But I get an error stating "'accentColor' is unavailable in macOS". Any way to achieve the same goal in MacOS? .foregroundColor only changes text colour but not the caret.
Upvotes: 5
Views: 1770
Reputation: 14060
This isn't available yet. I submitted FB8988194
to Apple to make it so accentColor
sets the cursor color like on iOS.
The only way to do it is to use a NSViewRepresentable
and set it in your NSTextField
like this:
struct YourCustomField: NSViewRepresentable{
func makeNSView(context: Context) -> NSTextField {
let textField = FancyTextField()
...
}
func updateNSView(_ nsView: NSTextField, context: Context) {
...
}
}
class FancyTextField: NSTextField {
override func becomeFirstResponder() -> Bool {
let textView = window?.fieldEditor(true, for: nil) as? NSTextView
textView?.insertionPointColor = NSColor(named: "YourColorName")!
return super.becomeFirstResponder()
}
}
If anyone knows of a pure-SwiftUI way, I'm eager to learn of it.
Upvotes: 0
Reputation: 257493
Here is worked solution. Tested with Xcode 12b
if #available(OSX 10.16, *) {
TextField("Placeholder", text: self.$text)
.accentColor(.red)
} else {
TextField("Placeholder", text: self.$text)
.colorMultiply(.red)
}
Upvotes: 5