首页 > 解决方案 > 用户点击按钮时如何清除输入的文本字段?

问题描述

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

标签: iosobjective-cswift3uitextfield

解决方案


如果你不想使用 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直接的子视图。如果 textfields 是 other 的子视图,则customview应该使用它customview而不是self.view


推荐阅读