开发者

iOS Detect User Touch Release

This may have been posted here somewhere but I can't find it. I am writing a simple iOS app with two UIViews. The user will first press and hold a certain area of the screen then release their touch on it then quickly touching a second view below.

The first UIView has a UILongPressGestureRecognizer attached to it and works fine. The second UIView has a UITapGestureRecognizer attached to it and also works fine. I cannot however, get either of these gesture recognizers to return anything that states that the user released their touch.

I have tried this code to no avail:

- (void)holdAction:(UILongPressGestureRecognizer *)holdRecognizer
{
    if (开发者_如何学PythonUIGestureRecognizerStateRecognized) {
        holdLabel.text = @"Holding Correctly. Release Touch when ready.";
        holdView.backgroundColor = [UIColor greenColor];
    } else if (UIGestureRecognizerStateCancelled){
        holdLabel.text = @"Ended";
        holdView.backgroundColor = [UIColor redColor];
}

Any suggestions would be great and especially if someone knows how to implement a call that returns the state of a user touching the device. I've looked over the developer docs and have come up empty.


After tinkering for a couple hours, I found a way that is working, not sure if its the best way to do it. Turns out I need to be writing it like the code below. I wasn't calling the specific UIGestureRecognizer I was declaring in the viewDidLoad() method.

- (void)holdAction:(UILongPressGestureRecognizer *)holdRecognizer
{
    if (holdRecognizer.state == UIGestureRecognizerStateBegan) {
        holdLabel.text = @"Holding Correctly. Release when ready.";
        holdView.backgroundColor = [UIColor greenColor];
    } else if (holdRecognizer.state == UIGestureRecognizerStateEnded)
    {
        holdLabel.text = @"You let go!";
        holdView.backgroundColor = [UIColor redColor];
    }
}


You need to use manual touch handling here (as opposed to using a gesture recognizer). Any UIResponder subclass can implement the following four methods:

– touchesBegan:withEvent:
– touchesMoved:withEvent:
– touchesEnded:withEvent:
– touchesCancelled:withEvent:

By using these methods, you get access to every phase of the touch events. You might have to implement your own logic to detect the long press, but you have full access to all touches.

For more information on touch handling, this session from WWDC 2011 is golden (requires dev account):

https://developer.apple.com/itunes/?destination=adc.apple.com.8270634034.08270634040.8367260921?i=1527940296


Swift 4+

 let gesture = UILongPressGestureRecognizer(target: self, action:  #selector(self.checkAction))
    self.view.addGestureRecognizer(gesture)


     @objc func checkAction(sender : UILongPressGestureRecognizer) {
        if sender.state == .ended || sender.state == .cancelled || sender.state == .failed {

        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜