简体   繁体   English

Swift 4-按下按钮时动作-循环播放?

[英]Swift 4 - Action while button pressed - loop?

Hi i want to send a command to a motor at my raspberry while a button is pressed. 嗨,我想在按下按钮的同时向树莓派的电动机发送命令。 So for example: While I press the button, the motor should run. 例如:当我按下按钮时,电动机应该运转。 It is a stepper motor, so I want long tap and normal tap commands. 这是一个步进电机,所以我需要长按和常规按命令。 Normal tap is easy and work, but the long tap (repeatedly commands) doesn't work. 普通轻按既容易又有效,但是长按(反复执行命令)不起作用。 I tried it with the long tap gesture recognizer and loops but it doesn't work Here's my code. 我用长按手势识别器尝试了一下并循环,但它不起作用这是我的代码。

@objc func motorLongTap(_ sender: UIGestureRecognizer){        
    while (sender.state == .began) && (sender.state != .ended){
    //send command
    }
}

The loop doesn't stop. 循环不会停止。 Hope somebody can help me. 希望有人能帮助我。 Best Regards 最好的祝福

EDIT: Problem solved. 编辑:问题解决了。 Thank you MadProgrammer for your solution 谢谢MadProgrammer的解决方案

Here is now the code to get a "loop" when action is pressed. 现在,这里是按下动作时获得“循环”的代码。

var buttonTimer:Timer!

@objc func motorLongTap(_ sender: UIGestureRecognizer){        
    if sender.state == .ended{
    buttonTimer.invalide()
    }
    else sender.state == .began{
    buttonTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(longTapMotor), userInfo: nil, repeats: true)
    }

}
    @objc func longTapMotor() {
        //send command
    }

Your logic is incorrect. 您的逻辑不正确。 Try this: 尝试这个:

@objc func motorLongTap(_ sender: UIGestureRecognizer){        
    if sender.state != .ended{
        //send command
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM