Is it possible to customize the image of the clear button in a UITextField
? I have a dark textfield background and the \"x\" is not visible enough.
Swift 2.2+ / iOS 9+ version of @Brody Robertson's answer:
let defaultClearButton = UIButton.appearanceWhenContainedInInstancesOfClasses([UITextField.self])
defaultClearButton.setBackgroundImage(UIImage(named: "ClearIcon"), forState: UIControlState.Normal)
You can access that property using KVO:
UIButton *clearButton = [myTextField valueForKey:@"_clearButton"];
[clearButton setImage:[UIImage new] forState:UIControlStateNormal];
You can set your own custom clear button to the text field's rightView
property. Make sure set the rightViewMode
property to UITextFieldViewModeWhileEditing
or UITextFieldViewModeAlways
, whatever makes sense for your case.
If the button's position isn't right for your need, you can subclass UITextField
and override the rightViewRectForBounds:
method.
The documentation says the default for the clearButtonMode
property is UITextFieldViewModeNever
, but I suspect Interface Builder may set it to UITextFieldViewModeWhileEditing
- Make sure you set it to the "never" value so it doesn't appear.
All these properties are documented in UITextField Class Reference.
depends on @Tuss László's answer
Swift 3.0
myTextField.clearButtonMode = .whileEditing
if let clearButton = myTextField.value(forKeyPath: "_clearButton") as? UIButton {
clearButton.setImage(UIImage(named:"myImage"), for: .normal)
clearButton.setImage(UIImage(named:"myImage"), for: .highlighted)
}
But really use it carefully. If Apple change implementations in future iOS releases, it would not be work
One approach would be to create a custom UITextField
that has your desired image as a subview and clears the parent text field when tapped. You disable the default button and add your custom behavior in this custom text field.
This should get you started. If there are any more concrete questions, feel free to edit your question or comment here if it's a minor problem.
Tested iOS7.0 - 8.4
It is possible to update the backgroundImage of all clear buttons using the following UIAppearance method. Unfortunately you cannot update the image of the button:
UIButton *defaultClearButton = [UIButton appearanceWhenContainedIn:[UITextField class], nil];
[defaultClearButton setBackgroundImage:[UIImage imageNamed:@"clearButtonBkg1.png"] forState:UIControlStateNormal];
Using the following images, this results in the following clear button:
White background image @3x:
Note: This will update the background image of ALL buttons contained in textfields