UIBarButtonItem长按/短按

时间:2019-01-27 04:43:47

标签: ios swift uigesturerecognizer uibarbuttonitem

我已经浏览了有关此主题的现有问题,在iOS 11之后似乎没有任何答案(这似乎打断了手势识别器)。

是否可以检测UIBarButtonItem上的短按/长按? Apple在“页面,数字,撤消/重做的主题演讲”中使用了此功能。

2 个答案:

答案 0 :(得分:1)

只需将默认事件处理程序替换为tap事件

-(void)handlerForBarButton:(UIBarButtonItem*)p_Sender

及其扩展版本

-(void)handlerForBarButton:(UIBarButtonItem*)p_Sender forEvent:(UIEvent*)p_Event

通过检查UIEvent对象,您可以了解该事件是否是长按(第一个UITouch对象的tapCount为0)。

这是我的播放速率按钮的代码,如果长条按钮项被按下约一秒钟,则该速率将速率返回“ 1x”:

/*
 rateButtonPressed:forEvent:

 */
- (IBAction)rateButtonPressed:(UIBarButtonItem*)p_Sender
                     forEvent:(UIEvent*)p_Event
{
    UITouch*    firstTouch = nil;
    if (   (nil != ((firstTouch = p_Event.allTouches.allObjects.firstObject)))
        && (0 == firstTouch.tapCount))
    {
        self.avAudioPlayer.rate = 1.0;
    }
    else
    {   // Default tap
        if (2.0 == self.avAudioPlayer.rate)
        {
            self.avAudioPlayer.rate = 0.5;
        }
        else
        {
            self.avAudioPlayer.rate += 0.25;
        }
    }
    [WBSettingsSharedInstance.standardUserDefaults setDouble:self.avAudioPlayer.rate
                                                      forKey:@"audioPlayerRate"];
    [self updateRateBarButton];
}

答案 1 :(得分:0)

尝试

@IBOutlet weak var btn: UIButton!

override func viewDidLoad() {

    let tapGesture = UITapGestureRecognizer(target: self, #selector (tap))  //Tap function will call when user tap on button
    let longGesture = UILongPressGestureRecognizer(target: self, #selector(long))  //Long function will call when user long press on button.
    tapGesture.numberOfTapsRequired = 1
    btn.addGestureRecognizer(tapGesture)
    btn.addGestureRecognizer(longGesture)
}

@objc func tap() {
     print("Single tap done")
}

@objc func long() {
     print("Long gesture recognized")
}