iOS Detect tap down and touch up of a UIView

前端 未结 5 2103
忘掉有多难
忘掉有多难 2020-12-01 05:06

I am stuck with a problem of determining how to detect a UIView being touched down and UIView being tapped. When it is touched down, I want the UIView to change its backgrou

5条回答
  •  既然无缘
    2020-12-01 05:59

    This method does not require subclassing anything. You just add a UILongPressGestureRecognizer to the view and set the minimumPressDuration to zero. Then you check the state when the gesture events are called to see if the touch event is beginning or ending.

    Here is the entire project code for the example image above.

    import UIKit
    class ViewController: UIViewController {
        @IBOutlet weak var myView: UIView!
        override func viewDidLoad() {
            super.viewDidLoad()
            let tap = UILongPressGestureRecognizer(target: self, action: #selector(tapHandler))
            tap.minimumPressDuration = 0
            myView.addGestureRecognizer(tap)
        }
    
        @objc func tapHandler(gesture: UITapGestureRecognizer) {
            
            // there are seven possible events which must be handled
    
            if gesture.state == .began {
                myView.backgroundColor = UIColor.darkGray
                return
            }
    
            if gesture.state == .changed {
                print("very likely, just that the finger wiggled around while the user was holding down the button. generally, just ignore this")
                return
            }
    
            if gesture.state == .possible || gesture.state == .recognized {
                print("in almost all cases, simply ignore these two, unless you are creating very unusual custom subclasses")
                return
            }
    
            // the three remaining states are
            // .cancelled, .failed, and .ended
            // in all three cases, must return to the normal button look:
            myView.backgroundColor = UIColor.lightGray
        }
    }
    

    Thanks to this answer for the idea.

提交回复
热议问题