SwiftUI TextField cursor colour
Asked Answered
E

4

34

Currently the cursor/caret for my SwiftUI TextField is blue. Is there an API for cursor colour or a workaround?

Estrous answered 20/10, 2019 at 0:27 Comment(0)
E
63

EDIT: as pointed out below and in the documentation, my original answer (below) is now deprecated and you should use .tint instead. Or if you want all text fields and other UI elements in your app to be the same you can customize your app’s global accentColor.

Original answer:

Tried it out and .accentColor does the trick.

TextField(" Enter some text", text: $name)
    .accentColor(.yellow)
Ethnography answered 20/10, 2019 at 3:53 Comment(6)
Didn't work for me but I'm trying this inside a Catalyst app (i.e., it's not a fully native AppKit macOS app) which might explain it :-(Perfectly
Unfortunately this isn't available before macOS 11 (it is available in iOS 13, however).Speechmaker
Also in the future Apple docs as of (Jan '22) specify that .accentColor() will be deprecated in the future, and to use this instead: .tint(.Yellow)Chism
Using .tint is not working for me. Only .accentColor works.Mouldy
iOS 16.0 .accentColor iOS 16.1 and higher .tint I use both to support all versions of 16Flapjack
for me not working both accentColor & tintColor , please helpEurope
S
6

The other answer didn't work for me but this did! It doesn't look like the cursor plays well with SwiftUI custom line spacing however...

extension NSTextView {
    open override var frame: CGRect {
        didSet {
            insertionPointColor = .black
        }
    }
}
Shorn answered 8/3, 2021 at 22:9 Comment(0)
R
1

For Xcode 15, I just use the Assets resources, I added a Cursor color set. And I use it on the tint modifier.

enter image description here

For example

import SwiftUI

struct MyTextFieldStyle: TextFieldStyle {
    
    func _body(configuration: TextField<Self._Label>) -> some View {
        configuration
            .tint(Color(.cursor))
    }
}

And you can use it in the textFieldStyle() modifier like

.textFieldStyle(MyTextFieldStyle())
Ronnyronsard answered 13/6, 2023 at 11:45 Comment(0)
C
0

This for me worked to change the cursor color for TextEditor. I put the code below as my app initialiser, thus making all of my apps cursors (TextEditor) pink.

init() {
    UITextView.appearance().tintColor = .systemPink
}

At the time of writing I have Xcode 13.4.1

Carolynecarolynn answered 17/7, 2022 at 21:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.