简体   繁体   中英

how to differentiate click and press on UIButton iOS

I have one button which i am using to record video and take photo from camera.

On click i want to take picture and on press start video recording.

      [self.recordButton addTarget:self action:@selector(recordTouchCancel:) forControlEvents:UIControlEventTouchCancel];
  [self.recordButton addTarget:self action:@selector(recordTouchDown:) forControlEvents:UIControlEventTouchDown];
  [self.recordButton addTarget:self action:@selector(recordTouchUp:) forControlEvents:UIControlEventTouchUpInside];
  [self.recordButton addTarget:self action:@selector(recordTouchUp:) forControlEvents:UIControlEventTouchUpOutside];

Press to record is working perfect but not able to get click, how can i differentiate click and hold on UIButton.

Any suggestions ?

I think you might looking for UILongPressGestureRecognizer . I notice that the API automatically trigger the right event between the tap and long press.

Take a look at Apple doc about https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UILongPressGestureRecognizer_Class/index.html

There is an exemple :

- (void)viewDidLoad {
    // FRIST SET TARGET & SELECTOR TO BUTTON
    UILongPressGestureRecognizer * pressLong =  [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(takeVideo:)];
    [self.recordButton addGestureRecognizer:pressLong];
    [self.recordButton addTarget:self action:@selector(takePicture:) forControlEvents:UIControlEventTouchUpInside];
}


-(void)takePicture:(UIButton*) sender {
    // TAKE PIC
}


-(void)takeVideo : (UILongPressGestureRecognizer*) gesture   {

    NSInteger state = gesture.state;

    switch (state) {
        case UIGestureRecognizerStateChanged: break;
        case UIGestureRecognizerStateBegan:
             //START RECORD
            break;
        case UIGestureRecognizerStateEnded:
             //END RECORD
            break;
    }

}

"UIControlEventTouchDown" and "UIControlEventTouchUpInside" are 2 different state. when you start to tab button "UIControlEventTouchDown" is called and when you give you finger "UIControlEventTouchUpInside" is called.and time between start and end of your tap there is no other state. So you can't do by this way.

But you can try "UIControlEventTouchDownRepeat" state. this is called when user tap twice on a button.

In you situation it better to use "tapGuesture"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM