Liftoff
Liftoff

Reputation: 25412

Detecting UITouch outside of view

I have a UIButton which is acting as a "confirm" button. Basically, I want it to require two taps to trigger its action, so the first time you tap it, the picture will change to an "are you sure" type image, at which point, a second tap would trigger the action.

This works fine, but I want to set it up so that tapping anywhere outside of the button resets it back to the first image again so it requires 2 taps again.

Is there any way to detect if the user touches outside of a UIButton; perhaps is there a way to give it "focus" and check for a focus exit?

I thought of UITouch, but that will only send its event to the view you are touching that responds to it.

Upvotes: 0

Views: 978

Answers (3)

larva
larva

Reputation: 5148

You can add UITapGestureRecognizer to get user touch outside button event

@interface YourViewController ()
@property NSInteger tapCount;
@property (weak) UITapGestureRecognizer *gestureRecognizer;
@end

add UITapGestureRecognizer

- (IBAction)buttonPressed:(id)sender {
    self.tapCount ++;
    if (self.tapCount == 1) {
        // change button label, image here

        // add gesture gesture recognizer
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOutSideAction)];
        [tap setNumberOfTapsRequired:1];
        [[[UIApplication sharedApplication] keyWindow] addGestureRecognizer:tap];
        self.gestureRecognizer = tap;
    } else if (self.tapCount == 2) {
        // tap two times

        self.tapCount = 0;
    }
}

- (void)tapOutSideAction {
    // reset button label, image here

    // remove gesture recognizer
    self.tapCount = 0;
    [[[UIApplication sharedApplication] keyWindow] removeGestureRecognizer:self.gestureRecognizer];
}

Upvotes: 0

Duncan C
Duncan C

Reputation: 131491

Attach a UITapGestureRecognizer to the button's superview (probably the view controller's content view.) Set userInteractionEnabled to true. Put your code that resets the button in the handler for the tap gesture recognizer.

Upvotes: 2

Marcus Handley
Marcus Handley

Reputation: 182

As you know you can use UIControlEvent.touchUpInside for when the view is pressed

If you want to see when a press is outside of a view you can you UIControlEvent.touchUpOutside instead

button.addTarget(self, action:<SELECTOR>,forControlEvents: UIControlEvents.TouchUpOutside)

Upvotes: 0

Related Questions