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


Answers:


334

该按钮是UITextField该类提供的内置叠加层,但是从iOS 2.2 SDK开始,没有任何方法可以通过Interface Builder进行设置。您必须以编程方式启用它。

将以下代码行添加到某处(viewDidLoad例如):

目标C

myUITextField.clearButtonMode = UITextFieldViewModeWhileEditing;

斯威夫特5.0

myUITextField.clearButtonMode = .whileEditing

61

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

在此处输入图片说明

取自XCode 5.1


1
请注意,该问题专门询问有关2.2 SDK的问题,并指出此选项在更高版本的Interface Builder中可用。
克里斯托弗·约翰逊

48

迅捷4+:

textField.clearButtonMode = UITextField.ViewMode.whileEditing

甚至更短:

textField.clearButtonMode = .whileEditing

修复枚举类型。不能以大写字母开头。
T. Pasichnyk

35

您可以使用以下方法添加自定义清除按钮并控制大小和所有内容:

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];

7

斯威夫特4(改编自克里斯托弗·约翰逊的答案)

textfield.clearButtonMode = .always

textfield.clearButtonMode = .whileEditing

textfield.clearButtonMode = .unlessEditing

textfield.clearButtonMode = .never

7

目标C:

self.txtUserNameTextfield.myUITextField.clearButtonMode = UITextFieldViewModeWhileEditing;

斯威夫特:

txtUserNameTextfield.clearButtonMode = UITextField.ViewMode.WhileEditing;

6

这不起作用,像我一样做:

迅速:

customTextField.clearButtonMode = UITextField.ViewMode.Always

customTextField.clearsOnBeginEditing = true;

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

6

在Xcode 8(8A218a)上:

迅速:

textField.clearButtonMode = UITextField.ViewMode.whileEditing;

“ W”从大写字母变为非大写的“ w”。


0
  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

在Xcode版本8.1(8B62)上,可以直接在Attributes Inspector中完成。选择textField,然后从“属性检查器”中的“清除按钮”下拉框中选择适当的选项。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.