单击 UIBarButtonItem 时显示 UIMenu

Show UIMenu when single-tapping UIBarButtonItem

在iOS14中,UIMenu有新的API,现在可以附加到UIBarButtonItem,就像这样:

这是我的代码:

@IBOutlet weak var addButton: UIBarButtonItem! // The button is from the storyboard.

override func viewDidAppear(_ animated: Bool) {
    if #available(iOS 14.0, *) {
        let simpleAction : UIAction = .init(title: "Simple", image: nil, identifier: nil, discoverabilityTitle: nil, attributes: .init(), state: .mixed, handler: { (action) in
            self.addButtonActionPressed(action: .simple)
        })
        
        let advancedAction : UIAction = .init(title: "Advanced", image: nil, identifier: nil, discoverabilityTitle: nil, attributes: .init(), state: .mixed, handler: { (action) in
            self.addButtonActionPressed(action: .advanced)
        })
        
        let actions = [simpleAction, advancedAction]
        
        let menu = UIMenu(title: "", image: nil, identifier: nil, options: .displayInline, children: actions)
        
        addButton.primaryAction = nil
        addButton.menu = menu
    }
}

但问题是,当我按下按钮时,没有任何反应。 只有当我长按按钮时,它才会显示菜单。我在网上看到这段代码:

button.showsMenuAsPrimaryAction = true

但这对我没有帮助,因为Value of type 'UIBarButtonItem' has no member 'showsMenuAsPrimaryAction'

有什么解决办法吗?我正在使用 Xcode 12.0 beta 4 (12A8179i)。

我解决了这个问题。如果它发生在你们身上,这是你可以做的:

  • 尝试检查按钮是否有任何其他操作。如果有,它不会将菜单显示为主要操作。

  • 如果您使用故事板,请改用代码,例如:

    self.navigationItem.rightBarButtonItem = .init(systemItem: .add)
    // Then configure the menu of the item here, by doing:
    navigationItem.rightBarButtonItem!.menu = menu 
    // Replace 'menu' with your menu object.
    

如果您知道任何其他提示,请随时编辑此问题并添加它们。

这是为右 UIBarButtonItem 创建 UIMenu 的方法

//Initiate an array of UIAction.  
let actions = [
     UIAction(title: "Last month", identifier: UIAction.Identifier("last_montg"), handler: handler),
     UIAction(title: "6 months", identifier: UIAction.Identifier("six_month"), handler: handler),
     UIAction(title: "1 year", identifier: UIAction.Identifier("one_year"), handler: handler)
 ]

//Initiale UIMenu with the above array of actions.  
let menu = UIMenu(title: "menu",  children: actions)

//Create UIBarButtonItem with the initiated UIMenu and add it to the navigationItem.  
let rightBarButton = UIBarButtonItem(title: "", image: UIImage(systemName: "calendar"), menu: menu)
self.navigationItem.rightBarButtonItem = rightBarButton

//handler to intercept event related to UIActions.  
let handler: (_ action: UIAction) -> () = { action in 
  print(action.identifier)
  switch action.identifier.rawValue {
  case "last_month":
    print("last_month")
  case "six_month":
    print("six_month")
  case "one_year":
    print("one_year")
  default:
    break
  }
}