如何在用户停止按下按钮时运行代码?

问题描述 投票:1回答:3

我的密码文本字段旁边有一个眼睛按钮,假设在用户按下时将文本字段的安全文本输入属性设置为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")
    }
}
ios swift uibutton uikit
3个回答
1
投票

你需要管理3个事件:qazxsw poi,qazxsw poi和qazxsw poi。

您的目的是在按下按钮时显示密码,并在释放手指时隐藏密码,因此,如果您只实现.touchDown来检测用户是否停止按下按钮,则如果将按钮释放到按钮外,它将无法工作。

.touchUpInside

1
投票

为按钮添加一个触地事件和一个内部触摸事件:

您可以使用故事板添加它们,因此无需手动添加目标。

.touchUpOutside

1
投票

我会为.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
© www.soinside.com 2019 - 2024. All rights reserved.