7

我想处理UIButton触摸结束时发生的事件。我知道 UIControl 有一些实现触摸的事件(UIControlEventTouchDown、UIControlEventTouchCancel 等)。但除了UIControlEventTouchDownUIControlEventTouchUpInside之外,我什么也抓不到。

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

怎么了?

4

6 回答 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");
}
于 2013-03-27T19:32:40.310 回答
3

您需要创建自己的扩展自定义类UIButton。你的头文件应该是这样的。

@interface customButton : UIButton
{
}

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

然后制作你的实现文件

于 2013-03-27T19:42:52.533 回答
3

@Ramshad使用UIControl类的以下方法以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")
}
于 2017-03-08T11:45:18.113 回答
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
    }
}
于 2017-01-05T08:08:11.087 回答
0

只需为带有事件TouchDown:和主要操作的 UIButton 添加 IBOutletsTriggered:

- (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)");
}
于 2017-01-09T08:47:05.753 回答
0

斯威夫特 3.0 版本:

 let btn = UIButton(...)

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

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

}
于 2017-04-04T08:35:52.687 回答