How to define touch end event for UIButton?

I want to handle the event when the UIButton contact is completed. I know that UIControl has some touch events (UIControlEventTouchDown, UIControlEventTouchCancel, etc.). But I can not catch them, except for UIControlEventTouchDown and UIControlEventTouchUpInside .

My button is a subtask of some UIView. In UIView property set userInteractionEnabled : YES .

What's wrong?

+5
source share
6 answers

You can set “action goals” for your button according to 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");
}
+21

, UIButton. .

@interface customButton : UIButton
{
}

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

+3

I think it is easier

UILongPressGestureRecognizer *longPressOnButton = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressOnButton:)];
longPressOnButton.delegate = self;
btn.userInteractionEnabled = YES;
[btn addGestureRecognizer:longPressOnButton];



- (void)longPressOnButton:(UILongPressGestureRecognizer*)gesture
{
    // When you start touch the button
    if (gesture.state == UIGestureRecognizerStateBegan)
    {
       //start recording
    }
    // When you stop touch the button
    if (gesture.state == UIGestureRecognizerStateEnded)
    {
        //end recording
    }
}
0
source

Just add IBOutlets for UIButton with events TouchDown:and main actionTriggered:

- (IBAction)touchDown:(id)sender {
    NSLog(@"This will trigger when button is Touched");
}

- (IBAction)primaryActionTriggered:(id)sender {
    NSLog(@"This will trigger Only when touch end within Button Boundary (not Frame)");
}
0
source

@Ramshad accepted the answer in Swift 3.0 syntax using the following method of the 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")
}
0
source

Swift version 3.0:

 let btn = UIButton(...)

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

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

}
0
source

All Articles