iOS Detect tap down and touch up of a UIView

前端 未结 5 2111
忘掉有多难
忘掉有多难 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:41

    Thanks to Holly's answer I built a ButtonView convenience class.

    Edit: As this answer says, UILongPressGestureRecognizer reacts quite faster so I updated my class.

    Usage:

    let btn = ButtonView()
    btn.onNormal = { btn.backgroundColor = .clearColor() }
    btn.onPressed = { btn.backgroundColor = .blueColor() }
    btn.onReleased = yourAction // Function to be called
    

    Class:

    /** View that can be pressed like a button */
    
    import UIKit
    
    class ButtonView : UIView {
    
        /* Called when the view goes to normal state (set desired appearance) */
        var onNormal = {}
        /* Called when the view goes to pressed state (set desired appearance) */
        var onPressed = {}
        /* Called when the view is released (perform desired action) */
        var onReleased = {}
    
        override init(frame: CGRect)
        {
            super.init(frame: frame)
    
            let recognizer = UILongPressGestureRecognizer(target: self, action: Selector("touched:"))
            recognizer.delegate = self
            recognizer.minimumPressDuration = 0.0
            addGestureRecognizer(recognizer)
            userInteractionEnabled = true
    
            onNormal()
        }
    
        func touched(sender: UILongPressGestureRecognizer)
        {
            if sender.state == .Began {
                onPressed(self)
            } else if sender.state == .Ended {
                onNormal(self)
                onReleased()
            }
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    

提交回复
热议问题