How can you add a UIGestureRecognizer to a UIBarButtonItem as in the common undo/redo UIPopoverController scheme on iPad apps?

后端 未结 15 1555
被撕碎了的回忆
被撕碎了的回忆 2020-12-07 12:36

Problem

In my iPad app, I cannot attach a popover to a button bar item only after press-and-hold events. But this seems to be standard for

15条回答
  •  抹茶落季
    2020-12-07 12:45

    Until iOS 11, let barbuttonView = barButton.value(forKey: "view") as? UIView will give us the reference to the view for barButton in which we can easily add gestures, but in iOS 11 the things are quite different, the above line of code will end up with nil so adding tap gesture to the view for key "view" is meaningless.

    No worries we can still add tap gestures to the UIBarItems, since it have a property customView. What we can do is create a button with height & width 24 pt(according to Apple Human Interface Guidelines) and then assign the custom view as the newly created button. The below code will help you perform one action for single tap and another for tapping bar button 5 times.

    NOTE For this purpose you must already have a reference to the barbuttonitem.

    func setupTapGestureForSettingsButton() {
          let multiTapGesture = UITapGestureRecognizer()
          multiTapGesture.numberOfTapsRequired = 5
          multiTapGesture.numberOfTouchesRequired = 1
          multiTapGesture.addTarget(self, action: #selector(HomeTVC.askForPassword))
          let button = UIButton(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
          button.addTarget(self, action: #selector(changeSettings(_:)), for: .touchUpInside)
          let image = UIImage(named: "test_image")withRenderingMode(.alwaysTemplate)
          button.setImage(image, for: .normal)
          button.tintColor = ColorConstant.Palette.Blue
          settingButton.customView = button
          settingButton.customView?.addGestureRecognizer(multiTapGesture)          
    }
    

提交回复
热议问题