Change color of cursor in UITextField

2019-01-13 08:20发布

问题:

How can I change the color of the cursor in my UITextField?

回答1:

With iOS 7 you can simply change tintColor property of the UITextField. This will affect both the color of the text cursor and the text selection highlight color.

You can do this in code ...

textField.tintColor = [UIColor redColor];

...

In Swift 4:

textField.tintColor = UIColor.red

...or in Interface Builder:

You can also do this for all text fields in your app using the UITextField appearance proxy:

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

In Swift 4:

UITextField.appearance().tintColor = UIColor.red

Below are simulator screenshots showing what an otherwise ordinary iOS 7 text field looks like with its tint set to red.

Text cursor screenshot:

Text selection screenshot:



回答2:

In iOS, UITextfield has a textInputTraits property. One of the private properties of UITextInputTraits is insertionPointColor.

Because it's an undocumented property, setting a custom color will probably get your app rejected from the App Store. If that's not a concern, this should work:

[[addNewCategoryTextField textInputTraits] setValue:[UIColor redColor]
                                             forKey:@"insertionPointColor"];


回答3:

[[self.searchTextField valueForKey:@"textInputTraits"] setValue:[UIColor redColor] forKey:@"insertionPointColor"];


回答4:

If you are developing on Mac OS X, then you can try the setInsertionPointColor: method. See NSTextView reference for more details.



回答5:

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.

It is drastically different from [addNewCategoryTextField textInputTraits].

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.



回答6:

To change the cursor color throughout the app for UITextField/UITextView, appearance proxy can also be used as below,

UITextField.appearance().tintColor = .green
UITextView.appearance().tintColor  = .green