如何在用户点击按钮时清除输入的文本字段?

How to clear the Entered textfield when the user taps on the button?

我正在处理注册表,当用户点击按钮时填写多个文本字段后,文本字段应该是清晰的。

swift

创建 IBOutletCollections 或将所有文本字段添加到一个数组 例如

 @IBOutlet var storeAllTexts: [UITextField]!

在您的按钮操作方法上,调用以下内容

   storeAllTexts.forEach { [=11=].text = "" }

objective C

创建 IBOutletCollections

 @property (nonatomic, strong) IBOutletCollection(UITextField) NSArray *storeAllTexts;

在您的按钮操作上

 for (UITextField *getCurrentText in self.storeAllTexts) {
  getCurrentText.text = @"";
}

对于示例,您得到 SO duplicate answer

如果不想用UITextField集合,可以用这个,

@IBAction func buttontapped(_ sender: Any) {
    self.view.subviews.forEach({ item in
        if item.isKind(of: UITextField.self) {
            let txtItem = item as! UITextField
            txtItem.text = ""
        }
    })
}

更新 正如@vacawama 建议的那样,

@IBAction func buttontapped(_ sender: Any) {
    for case let txtItem as UITextField in self.view.subviews {
        txtItem.text = ""
    }
}

假设:所有文本框都是self.view的直接子视图。如果文本字段是其他 customview 的子视图,您应该使用 customview 而不是 self.view

对于Objective C

for (id view in [self.view subviews])                                              
{
    if ([view isKindOfClass:[UITextField class]])                                       
    {
        UITextField *textField = (UITextField *)view;
        textField.text = @"";
    }
 }