After Add a CustomView to navigationItem, CustomView always return nil

旧城冷巷雨未停 提交于 2020-05-17 07:29:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!