What was answered before is not true anymore. Now there are context menus.
With iOS13 there was UIMenu
introduced and with iOS14 UIBarButtonItem
has a menu
property for that you can set a UIMenu
. The menu you set there, will pop up when tapping the UIBarButtonItem
. (see also https://developer.apple.com/documentation/uikit/uibarbuttonitem/3601188-menu)
You do not need to set any other action on the UIBarButtonItem
(see line before last line in my sample code, action
is nil
).
Here is an example for having a rightBarButtonItem
triggering a menu with four items.
let menuHandler: UIActionHandler = { action in
print(action.title)
}
let barButtonMenu = UIMenu(title: "", children: [
UIAction(title: NSLocalizedString("Identify Plant", comment: ""), image: UIImage(systemName: "viewfinder"), handler: menuHandler),
UIAction(title: NSLocalizedString("Plant's diary", comment: ""), image: UIImage(systemName: "books.vertical"), handler: menuHandler),
UIAction(title: NSLocalizedString("Plant's notifications", comment: ""), image: UIImage(systemName: "bell"), handler: menuHandler),
UIAction(title: NSLocalizedString("Remove plant", comment: ""), image: UIImage(systemName: "trash"), handler: menuHandler)
])
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Manage", style: .plain, target: self, action: nil)
navigationItem.rightBarButtonItem?.menu = barButtonMenu
// or using the initializer
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Manage", image: nil, primaryAction: nil, menu: barButtonMenu)
My answer is based on this great sample code article: https://developer.apple.com/documentation/uikit/uinavigationcontroller/customizing_your_app_s_navigation_bar