自定义UITextField的clearButton

/ 0评 / 0

UITextField 的 clearButtonMode 样式为黑色叉叉按钮,如果 UITextField 背景颜色也设置为深色的话,就没法看清了。但是系统并没有提供修改 clearButtonMode 样式的方法,但我们可以通过设置他的 rightView 来实现这个功能。

代码实现

我使用 extension 来实现这个功能。

// MARK: - 添加自定义清除按钮
extension UITextField {
    
    /// 给uitextfield添加一个清除按钮
    func setModifyClearButton() {
        let clearButton = UIButton(type: .custom)
        clearButton.setImage(UIImage(named: "textfield_clear_btn"), for: .normal)
        clearButton.frame = CGRect(x: 0, y: 0, width: 35, height: 35)
        clearButton.contentMode = .scaleAspectFit
        clearButton.addTarget(self, action: #selector(UITextField.clear(sender:)), for: .touchUpInside)
        self.rightView = clearButton
        self.rightViewMode = .whileEditing
    }
    
    /// 点击清除按钮,清空内容
    func clear(sender : AnyObject) {
        self.text = ""
    }
    
}

如何使用

public lazy var textField: UITextField = {
    let textField = UITextField()
    textField.textColor = UIColor.colorWithHexString("FFFFFF")
    textField.clearButtonMode = .never
    textField.setModifyClearButton() // 添加自定义清除按钮
    return textField
}()

效果如下:

1

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注