9

在 iOS 14 中,有新的 API UIMenu,现在可以附加到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)。

4

3 回答 3

8

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

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

  • 如果您使用情节提要,请改用代码,例如:

    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.
    

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

于 2020-08-08T15:39:45.777 回答
2

这是为正确的 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
  }
}
于 2021-10-08T17:48:22.257 回答
1

还要确保在 UIButton 上没有添加其他操作,为 UIMenu 设置的 UIButton 不应该有任何操作。

于 2022-03-02T10:40:05.343 回答