如何在UITextField的右侧添加清除文本的小"X"按钮?我找不到在iPhone OS 2.2 SDK中在Interface Builder中添加此子控件的属性.
注意:在Xcode 4.x及更高版本(iPhone 3.0 SDK及更高版本)中,您可以在Interface Builder中执行此操作.
此按钮是由UITextField类提供的内置覆盖,但是从iPhone OS 2.2 SDK开始,没有任何方法可以通过Interface Builder进行设置.您必须以编程方式启用它.
在某处添加这行代码(例如viewDidLoad):
myUITextField.clearButtonMode = UITextFieldViewModeWhileEditing;
更新:最新版本的Xcode IB确实支持此属性.
您也可以直接在Attributes Inspector下的Interface Builder中设置它.
取自XCode 5.1
斯威夫特3:
textField.clearButtonMode = UITextField.ViewMode.whileEditing
甚至更短:
textField.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];
目标C:
self.txtUserNameTextfield.myUITextField.clearButtonMode = UITextFieldViewModeWhileEditing;
斯威夫特:
txtUserNameTextfield.clearButtonMode = UITextField.ViewMode.WhileEditing;
斯威夫特4(改编自克里斯托弗·约翰逊的答案)
textfield.clearButtonMode = .always textfield.clearButtonMode = .whileEditing textfield.clearButtonMode = .unlessEditing textfield.clearButtonMode = .never
这不起作用,跟我一样:
迅速:
customTextField.clearButtonMode = UITextField.ViewMode.Always customTextField.clearsOnBeginEditing = true; func textFieldShouldClear(textField: UITextField) -> Bool { return true }
在Xcode 8(8A218a)上:
迅速:
textField.clearButtonMode = UITextField.ViewMode.whileEditing;
“ W”从大写字母变为非大写的“ w”。