【问题标题】:How to clear the Entered textfield when the user taps on the button? [closed]用户点击按钮时如何清除输入的文本字段? [关闭]
【发布时间】:2018-11-11 11:00:38
【问题描述】:

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

【问题讨论】:

标签: ios objective-c swift3 uitextfield


【解决方案1】:

对于目标 C

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

【讨论】:

    【解决方案2】:

    如果不想使用 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

    【讨论】:

    • 这太棒了 answer.upVoted!
    • @AbecedarioPoint 非常感谢
    • for case let txtItem as UITextField in self.view.subviews { txtItem.text = "" }
    • @vacawama 谢谢,让我更新我的答案
    • 在任何一种情况下,如果UITextFields 是另一个视图的子视图(如UIScrollViewUIStackView),OP 可能必须用另一个视图替换self.view
    【解决方案3】:

    迅速

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

     @IBOutlet var storeAllTexts: [UITextField]!
    

    在您的按钮操作方法上,调用以下代码

       storeAllTexts.forEach { $0.text = "" }
    

    目标 C

    创建 IBOutletCollections

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

    关于您的按钮操作

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

    如需样品,请获取SO duplicate answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多