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?
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");
}
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
@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")
}
Swift 3.0 version:
let btn = UIButton(...)
btn.addTarget(self, action: #selector(MyView.onTap(_:)), for: .touchUpInside)
func onTap(_ sender: AnyObject) -> Void {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With