Change UITextField and UITextView Cursor / Caret C

2019-01-16 03:09发布

I'm wondering about changing the color of the cursor / caret in a UITextField (And UITextView if its the same answer) in iOS. I've seen answers for OSX development, but nothing for iOS.

Is this even possible?

13条回答
霸刀☆藐视天下
2楼-- · 2019-01-16 03:38

If you're targeting iOS 7+, this has been made much easier. Simply change the tintColor of the field with a cursor using the appearance proxy and it will apply throughout the app:

Swift 3.0:

UITextField.appearance().tintColor = .black 

Objective-C:

[[UITextField appearance] setTintColor:[UIColor blackColor]];

Same answer applies for an individual UITextView:

Swift 3.0:

myTextField.tintColor = .black 

Objective-C

[myTextField setTintColor:[UIColor blackColor]];
查看更多
仙女界的扛把子
3楼-- · 2019-01-16 03:38

This worked for me in swift:

UITextField.tintColor = UIColor.blackColor()

You can also set this in storyboard: https://stackoverflow.com/a/18759577/3075340

查看更多
男人必须洒脱
4楼-- · 2019-01-16 03:38

Durgesh's approach does work.

I also used such KVC solutions many times. Despite it seems to be undocumented, but it works. Frankly, you don't use any private methods here - only Key-Value Coding which is legal.

P.S. Yesterday my new app appeared at AppStore without any problems with this approach. And it is not the first case when I use KVC in changing some read-only properties (like navigatonBar) or private ivars.

查看更多
仙女界的扛把子
5楼-- · 2019-01-16 03:39

If the UITextField is from UISearchBar then first get the textField from searchBar and then apply tintColor property:

let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField
textFieldInsideSearchBar?.tintColor = UIColor.lightGray
查看更多
6楼-- · 2019-01-16 03:40

For Interface Builder version with Swift

@IBOutlet weak var tvValue: UITextView! {
        didSet {
            tvValue.tintColor = .black
        }
    }
查看更多
欢心
7楼-- · 2019-01-16 03:45

Note: This answer is out of date and should be used for pre-iOS 7 development only. See other answers for a 1 line solution using the appearance proxy in iOS 7.

I arrived at this question after I faced the same problem in a project I was working on.

I managed to create a solution that will be accepted by the AppStore review team as it does not use any existing Private APIs.

I have created a control called DGTextField that extends UITextField.

查看更多
登录 后发表回答