我的密码文本字段旁边有一个眼睛按钮,假设在用户按下时将文本字段的安全文本输入属性设置为false,它应该在用户移开他的手指时结束。
当用户使用带有touchUpInside事件的目标按下时,我成功设法将属性设置为false,但我不知道如何检测此事件已停止。这就是我要找的东西。
在此之前我使用了长按手势识别器,但问题是代码花了太多时间才开始。这是正常的,因为它是一个长期的预测,但它不是我想要的行为。
我的代码是:
let gesture = UILongPressGestureRecognizer(target: self, action: #selector(eyePressed(sender:)))
passwordEyeButton.addGestureRecognizer(gesture)
@objc func eyePressed(sender : UILongPressGestureRecognizer){
switch sender.state {
case .began :
passwordEyeButton.setImage(eyeImage, for: .normal)
passwordTextField.isSecureTextEntry = false
case .ended :
passwordEyeButton.setImage(crossedEyeImage, for: .normal)
passwordTextField.isSecureTextEntry = true
default :
print("default state")
}
}
你需要管理3个事件:qazxsw poi,qazxsw poi和qazxsw poi。
您的目的是在按下按钮时显示密码,并在释放手指时隐藏密码,因此,如果您只实现.touchDown
来检测用户是否停止按下按钮,则如果将按钮释放到按钮外,它将无法工作。
.touchUpInside
为按钮添加一个触地事件和一个内部触摸事件:
您可以使用故事板添加它们,因此无需手动添加目标。
.touchUpOutside
我会为.touchUpInside
添加两个目标,用于两个事件:
override func viewDidLoad() {
super.viewDidLoad()
button.addTarget(self, action: #selector(showPassword), for: .touchDown)
button.addTarget(self, action: #selector(hidePassword), for: .touchUpInside)
button.addTarget(self, action: #selector(hidePassword), for: .touchUpOutside)
}
@objc func showPassword(_ sender: Any) {
print("show password")
}
@objc func hidePassword(_ sender: Any) {
print("hide password")
}
处理//Touch down
@IBAction func touched(_ sender: UIButton) {
print("show password")
}
//Touch up inside
@IBAction func touchUp(_ sender: UIButton) {
print("hide password")
}
处理UIButton