簡體   English   中英

如何檢測UIButton的觸摸結束事件?

[英]How to detect touch end event for UIButton?

我想處理UIButton touch結束時發生的事件。 我知道UIControl有一些實現觸摸的事件(UIControlEventTouchDown,UIControlEventTouchCancel等)。 但除了UIControlEventTouchDownUIControlEventTouchUpInside,我無法捕獲它們。

我的按鈕是一些UIView的子視圖。 UIView將userInteractionEnabled屬性設置為YES

怎么了?

您可以根據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");
}

您需要創建自己的擴展UIButton的自定義類。 你的頭文件應該是這樣的。

@interface customButton : UIButton
{
}

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

然后制作你的實施文件

我認為這更容易

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

只需為UIButton添加帶有事件TouchDown: IBOutlets TouchDown:Triggered:主要操作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)");
}

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

Swift 3.0版本:

 let btn = UIButton(...)

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

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM