在iOS 14中,有新的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.0beta 4 (12A8179i)。
发布于 2020-08-08 15:39:45
我解决了这个问题。如果这件事发生在你们任何人身上,你们可以这样做:
如果使用情节提要,则使用代码,例如:
self.navigationItem.rightBarButtonItem = .init(systemItem:.add) //然后在这里配置项目的菜单,方法是: navigationItem.rightBarButtonItem!.menu =navigationItem.rightBarButtonItem //用菜单对象替换‘菜单’。
如果你知道任何其他技巧,可以随意编辑这个问题并添加它们。
发布于 2021-10-08 17:48:22
这是如何为正确的UIMenu创建UIBarButtonItem
//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
}
}https://stackoverflow.com/questions/63299837
复制相似问题