Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect touch end event for UIButton?

I want to handle an event occurs when UIButton touch is ended. I know that UIControl has some events implementing touches (UIControlEventTouchDown, UIControlEventTouchCancel, etc.). But I can't catch any of them except UIControlEventTouchDown and UIControlEventTouchUpInside.

My button is a subview of some UIView. That UIView has userInteractionEnabled property set to YES.

What's wrong?

like image 836
Brain89 Avatar asked Mar 27 '13 19:03

Brain89


4 Answers

You can set 'action targets' for your button according to the ControlEvents

- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;

Example:

[yourButton addTarget:self 
           action:@selector(methodTouchDown:)
 forControlEvents:UIControlEventTouchDown];

[yourButton addTarget:self 
           action:@selector(methodTouchUpInside:)
 forControlEvents: UIControlEventTouchUpInside];

-(void)methodTouchDown:(id)sender{

   NSLog(@"TouchDown");
}
-(void)methodTouchUpInside:(id)sender{

  NSLog(@"TouchUpInside");
}
like image 200
Shamsudheen TK Avatar answered Oct 20 '22 15:10

Shamsudheen TK


You need to create your own custom class that extends UIButton. your header file should look like this.

@interface customButton : UIButton
{
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;

then make your implementation file

like image 23
Alex Avatar answered Oct 20 '22 13:10

Alex


@Ramshad's accepted answer in Swift 3.0 syntax using following method of UIControl class

open func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControlEvents)

Example:

myButton.addTarget(self, action: #selector(MyViewController.touchDownEvent), for: .touchDown)
myButton.addTarget(self, action: #selector(MyViewController.touchUpEvent), for: [.touchUpInside, .touchUpOutside])

func touchDownEvent(_ sender: AnyObject) {
    print("TouchDown")
}

func touchUpEvent(_ sender: AnyObject) {
    print("TouchUp")
}
like image 29
Maverick Avatar answered Oct 20 '22 14:10

Maverick


Swift 3.0 version:

 let btn = UIButton(...)

 btn.addTarget(self, action: #selector(MyView.onTap(_:)), for: .touchUpInside)

 func onTap(_ sender: AnyObject) -> Void {

}
like image 27
Bary Levy Avatar answered Oct 20 '22 13:10

Bary Levy