问题
Bellow code is adding a customView to navigationItem
successfully, but when trying to access the customView
it always return nil
override func viewDidLoad() {
super.viewDidLoad()
let customView = getCustomView() // supposed that the function return a custom view
let actionButton = UIBarButtonItem(customView: customView)
self.navigationItem.rightBarButtonItem = actionButton // successfully added customView
print(navigationItem.rightBarButtonItem?.customView) // print always nil
}
Result :
nil
回答1:
I found out that the best way to access our customView
(custom rightBarButtonItem
), we have to access through Swift standard way:
After adding the customView, we can access the customView via : self.navigationItem.rightBarButtonItems
array only.
In my case to get customView back from navigationItem :
let customView = navigationItem.rightBarButtonItems?.first?.customView // access the first added customView
回答2:
let customView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
customView.backgroundColor = UIColor.blue// supposed that the function return a custom view
let actionButton = UIBarButtonItem(customView: customView)
self.navigationItem.rightBarButtonItem = actionButton // successfully added customView
print(navigationItem.rightBarButtonItem?.customView)
This works for me
来源:https://stackoverflow.com/questions/60183720/after-add-a-customview-to-navigationitem-customview-always-return-nil