Custom UITextField clear button

你说的曾经没有我的故事 提交于 2019-12-02 17:03:52
Danra

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.

You can access that property using KVO:

UIButton *clearButton = [myTextField valueForKey:@"_clearButton"];
[clearButton setImage:[UIImage new] forState:UIControlStateNormal];
Brody Robertson

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

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)
Pavel Volobuev

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

Swift 3

let customClearButton = UIButton.appearance(whenContainedInInstancesOf: [UITextField.self])
customClearButton.setBackgroundImage(UIImage(named: "custom_cb"), for: .normal)

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!