将“清除”按钮添加到iPhone UITextField

如何在清除文本的UITextField右侧添加小“ X ”按钮?我在iPhone OS 2.2 SDK的Interface Builder中找不到用于添加此子控件的属性。

__Xcode4.X及更高版本(iPhone3.0SDK及更高版本)中的ABC0,您可以在InterfaceBuilder中执行此操作。

131356 次浏览

此按钮是由UITextField类提供的内置覆盖,但在IOS 2.2 SDK中,无法通过Interface Builder对其进行设置。您必须以编程方式启用它。

将这行代码添加到某处(例如,viewDidLoad):

目标-C

myUITextField.clearButtonMode = UITextFieldViewModeWhileEditing;

SWIFT 5.0

myUITextField.clearButtonMode = .whileEditing

您可以添加自定义清除按钮,并使用此控制大小和每件事:

UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
[clearButton setImage:img forState:UIControlStateNormal];
[clearButton setFrame:frame];
[clearButton addTarget:self action:@selector(clearTextField:) forControlEvents:UIControlEventTouchUpInside];


textField.rightViewMode = UITextFieldViewModeAlways; //can be changed to UITextFieldViewModeNever,    UITextFieldViewModeWhileEditing,   UITextFieldViewModeUnlessEditing
[textField setRightView:clearButton];

您也可以直接从“属性”检查器下的“界面生成器”中进行设置。

enter image description here

取自Xcode 5.1

SWIFT 4+:

textField.clearButtonMode = UITextField.ViewMode.whileEditing

或者更短:

textField.clearButtonMode = .whileEditing

目标C:

self.txtUserNameTextfield.myUITextField.clearButtonMode = UITextFieldViewModeWhileEditing;

SWIFT:

txtUserNameTextfield.clearButtonMode = UITextField.ViewMode.WhileEditing;

这不管用,像我这样做:

迅速的:

customTextField.clearButtonMode = UITextField.ViewMode.Always


customTextField.clearsOnBeginEditing = true;


func textFieldShouldClear(textField: UITextField) -> Bool {
return true
}

在Xcode 8(8A218A)上:

SWIFT:

textField.clearButtonMode = UITextField.ViewMode.whileEditing;

“ W ”从大写变为非大写“ W ”。

在Xcode版本8.1(8B62)上,可以直接在属性检查器中完成。选择文本字段,然后从位于属性检查器中的“清除”按钮下拉框中选择相应的选项。

  func clear_btn(box_is : UITextField){
box_is.clearButtonMode = .always
if let clearButton = box_is.value(forKey: "_clearButton") as? UIButton {
let templateImage =  clearButton.imageView?.image?.withRenderingMode(.alwaysTemplate)


clearButton.setImage(templateImage, for: .normal)
clearButton.setImage(templateImage, for: .highlighted)


clearButton.tintColor = .white


}
}

斯威夫特4(根据Kristopher Johnson的回答改编)

textfield.clearButtonMode = .always


textfield.clearButtonMode = .whileEditing


textfield.clearButtonMode = .unlessEditing


textfield.clearButtonMode = .never

使用下面的代码行。如果有RightView,则不显示清除按钮。

self.txtField.rightView = nil
self.txtField.rightViewMode = .never
self.txtField.clearButtonMode = UITextField.ViewMode.always