单击任何其他字段或任何位置时删除清除按钮

时间:2022-11-19 09:31:59

I managed to show a custom clearbutton, the problem is that it will not be removed when clicking anywhere else or clicking other textfield. It is always showing.

我设法显示一个自定义的clearbutton,问题是当点击其他地方或点击其他文本字段时不会删除它。它总是显示出来。

Here is my extension:

这是我的扩展:

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 = ""
    }

}

and here i show the clearbutton on the method:

在这里我展示了方法的清晰按钮:

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
    }

I want it to be visible only when clicking inside the textfield.

我希望它只在文本字段内单击时才可见。

1 个解决方案

#1


0  

Replace this:

self.rightViewMode = .always

With:

self.rightViewMode = .whileEditing

#1


0  

Replace this:

self.rightViewMode = .always

With:

self.rightViewMode = .whileEditing