How can I change the color of the c开发者_C百科ursor in my UITextField
?
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:
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"];
[[self.searchTextField valueForKey:@"textInputTraits"] setValue:[UIColor redColor] forKey:@"insertionPointColor"];
If you are developing on Mac OS X, then you can try the setInsertionPointColor:
method. See NSTextView reference for more details.
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.
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
精彩评论