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

时间:2017-11-12 15:56:38

标签: ios swift uitextfield

我设法显示自定义清除按钮,问题是当点击其他地方或点击其他文本字段时不会删除它。它总是在显示。

这是我的扩展名:

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
    }

我希望只有在文本字段内单击时才能看到它。

1 个答案:

答案 0 :(得分:0)

替换它:

self.rightViewMode = .always

使用:

self.rightViewMode = .whileEditing