简体   繁体   中英

In swift, how do I detect when a press begins and end on a UILabel?

I want to be able to detect when a press begins so I can perform an action while it is pressed only, stopping that action when press ends.

I know there is a pressesBegan function on UILabels but I am not sure how to use it and can't seem to find examples.

You can use UILongPressGestureRecongizer.

Initialize the pressGestureRecongizer in the viewDidLoad method of your viewController and add it to the label:

let pressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: "handlePress:")
label.addGestureRecognizer(pressGestureRecognizer)

and then you define the handlePress-function

func handlePress(sender: UILongPressGestureRecognizer) {
    if sender.state == UIGestureRecognizerState.Began {
        // handle start of pressing
    }
    else if sender.state == UIGestureRecognizerState.Ended {
        // handle end of pressing
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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