Swift UIBarButtonItem添加Gesture Recognizer

时间:2017-11-09 04:26:27

标签: swift uigesturerecognizer uibarbuttonitem

我想在UIBarButtonItem添加长按手势识别器,但我不能。使用Storyboard是不可能的,addGestureRecognizer中也没有方法UIBarButtonItem

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

    //1. Create A UIButton Which Can Have A Gesture Attached
    let button = UIButton(type: .custom)
    button.frame = CGRect(x: 0, y: 0, width: 80, height: 40)
    button.setTitle("Press Me", for: .normal)

    //2. Create The Gesture Recognizer
    let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(doSomething))
    longPressGesture.minimumPressDuration = 1
    button.addGestureRecognizer(longPressGesture)

    //3. Create A UIBarButton Item & Initialize With The UIButton
    let barButton = UIBarButtonItem(customView: button)

    //4. Add It To The Navigation Bar
    self.navigationItem.leftBarButtonItem = barButton

当然,Selector方法将替换为您自己的方法。

答案 1 :(得分:0)

不适用于UIButton(iOS 12),但适用于UILabel:

private ApplicationContext context;

@PostMapping("/shutdown")
public void shutdownContext() {
    ((ConfigurableApplicationContext) context).close();
}

@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
    this.context = ctx;
}