如何检测UIButton的触摸结束事件?

7

我希望能够处理当UIButton触摸结束时发生的事件。我知道UIControl有一些实现触摸的事件(UIControlEventTouchDown,UIControlEventTouchCancel等),但是除了UIControlEventTouchDownUIControlEventTouchUpInside之外,我无法捕获任何一个事件。

我的按钮是某个UIView的子视图。该UIView的userInteractionEnabled属性设置为YES

出了什么问题?

6个回答

25

根据ControlEvents,您可以为按钮设置“操作目标”。

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

例子:

[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");
}

哦,它运行得很好。我的不注意给我开了个残酷的玩笑。谢谢。 - Brain89
谢谢。这个可行。但是如果用户在触摸时拖动,问题就出现了。TouchUpInside在那段时间内没有被调用 :( - Karan Alangat

3

你需要创建一个自定义类,继承UIButton。你的头文件应该像这样。

@interface customButton : UIButton
{
}

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

然后制作你的实现文件。

不幸的是,我的高级程序员禁止创建新类。但是这个解决方案也可以正常工作。 - Brain89

3

使用UIControl类的以下方法,@Ramshad在Swift 3.0语法中接受了答案

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

例子:

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")
}

1

Swift 3.0 版本:

 let btn = UIButton(...)

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

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

}

0

我认为这更容易

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

只需为带有事件的UIButton添加IBOutlets TouchDown:和Primary Action Triggered:

- (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)");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接