UITextField自定义清除按钮-键入前显示按钮

时间:2018-12-07 22:47:31

标签: ios swift uitextfield

我一直关注Custom Clear Button此处发布的扩展解决方案

清除按钮将在我输入文本字段后立即输入。这是不正确的行为。清除按钮应仅在键入文本时显示。该如何解决?

我正在从viewWillAppear的文本字段中调用applyCustomClearButton

extension UITextField {
    // Custom Clear Button
    func applyCustomClearButton() {
        clearButtonMode = .never
        rightViewMode   = .whileEditing

        let clearButton = UIButton(frame: CGRect(x: 0, y: 0, width: 16, height: 16))
        clearButton.setImage(UIImage(named: "Glyph/16x16/Clear")!, for: [])
        clearButton.addTarget(self, action: #selector(clearClicked), for: .touchUpInside)

        rightView = clearButton
    }

    @objc func clearClicked(sender:UIButton) {
        text = ""
    }
}

1 个答案:

答案 0 :(得分:0)

我有一种直觉,就是您没有调用applyCustomClearButton()函数。

为此,请转到具有您的UITextfield的viewcontroller并调用:

yourTextField.applyCustomClearButton()