monish
monish

Reputation: 453

Change color of cursor in UITextField

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

Upvotes: 42

Views: 43840

Answers (6)

Cap
Cap

Reputation: 2034

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:

screenshot showing how to modify tint of a text field 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 cursor screenshot

Text selection screenshot:

Text selection screenshot

Upvotes: 99

Kamran
Kamran

Reputation: 15238

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

Upvotes: 0

malex
malex

Reputation: 10096

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.

Upvotes: 2

Durgesh
Durgesh

Reputation: 113

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

Upvotes: 6

lemnar
lemnar

Reputation: 4053

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"];

Upvotes: 14

Laurent Etiemble
Laurent Etiemble

Reputation: 27889

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

Upvotes: 3

Related Questions