Triggering a UIButton's method when user drags finger into button's area?

前端 未结 3 1976
南方客
南方客 2021-01-18 12:46

I want to have a button that triggers its method under the following conditions:

  • When the user taps the button
  • When the user presses the button and dr
3条回答
  •  迷失自我
    2021-01-18 13:50

    Regarding:

    • When the user presses the button and drags his/her finger out of the button's area

    I recently have done something similar. Here is my code in Swift.

    (In this example you subclassed UIButton, like: class FadingButton: UIButton)

    ...
    
    // The user tapped the button and then moved the finger around.
    override func touchesMoved(_ touches: Set, with event: UIEvent?) {
        super.touchesMoved(touches, with: event)
    
        // Get the point to which the finger moved
        if let point: CGPoint = touches.first?.location(in: self) {
    
            // If the finger was dragged outside of the button...
            if ((point.x < 0 || point.x > bounds.width) ||
                (point.y < 0 || point.y > bounds.height)) {
    
                // Do whatever you need here
            }
        }
    }
    ...
    

    I hope it helps someone.

提交回复
热议问题