我设法显示自定义清除按钮,问题是当点击其他地方或点击其他文本字段时不会删除它。它总是在显示。
这是我的扩展名:
extension UITextField {
func clearButtonWithImage(_ image: UIImage) {
let clearButton = UIButton()
clearButton.setImage(image, for: .normal)
clearButton.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
clearButton.contentMode = .scaleAspectFit
clearButton.addTarget(self, action: #selector(self.clear(sender:)), for: .touchUpInside)
self.rightView = clearButton
self.rightViewMode = .always
}
func clear(sender: AnyObject) {
self.text = ""
}
}
在这里我展示了方法的清晰按钮:
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if textField == dateSearchTextField {
self.performSegue(withIdentifier: "showCalendar", sender: self)
textField.clearButtonWithImage(#imageLiteral(resourceName: "icClear"))
return false
} else if textField == timeSearchTextField {
self.performSegue(withIdentifier: "showTimePicker", sender: self)
textField.clearButtonWithImage(#imageLiteral(resourceName: "icClear"))
return false
}
return true
}
我希望只有在文本字段内单击时才能看到它。
答案 0 :(得分:0)
替换它:
self.rightViewMode = .always
使用:
self.rightViewMode = .whileEditing