jake9115
jake9115

Reputation: 4084

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

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

Basically, anytime any part of the button is touched, regardless of origin of touch, I want the method triggered, but want to accomplish this by manipulating UIButton properties, like touchedUpInside and such.

Thanks for the suggestions!

Upvotes: 6

Views: 4316

Answers (3)

backslash-f
backslash-f

Reputation: 8193

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<UITouch>, 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.

Upvotes: 3

Khaled Zayed
Khaled Zayed

Reputation: 316

You need to add the following UIControlEvents to your button:

  1. UIControlEventTouchUpInside
  2. UIControlEventTouchDragOutside
  3. UIControlEventTouchDragInside

as such

    [self.myButton addTarget:self action:@selector(dragMoving:withEvent: )
              forControlEvents: UIControlEventTouchDragInside | UIControlEventTouchDragOutside];

    [self.myButton addTarget:self action:@selector(dragEnded:withEvent: )
              forControlEvents: UIControlEventTouchUpInside |
     UIControlEventTouchUpOutside];

    [self.myButton addTarget:self action:@selector(myButtonTouchDown:withEvent: )
              forControlEvents: UIControlEventTouchDown];

Upvotes: 1

Divyu
Divyu

Reputation: 1313

Make you method such as -(IBAction)btnTap and connect to these properties

  • When the user taps the button. - Use Touch Down method for this
  • When the user presses the button and drags his/her finger out of the button's area - Use Touch Up Inside for this purpose
  • When the user drags his/her finger from outside the button's area to inside the button's - Touch Drag Inside

Upvotes: 2

Related Questions