将自定义视图添加到导航项后,自定义视图始终 return nil
After Add a CustomView to navigationItem, CustomView always return nil
下面的代码成功地向 navigationItem
添加了一个 customView,但是当试图访问 customView
时它总是 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
}
结果:
nil
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)
这对我有用
我发现访问我们的 customView
(自定义 rightBarButtonItem
)的最佳方式,我们必须通过 Swift 标准方式访问:
添加customView后,我们只能通过self.navigationItem.rightBarButtonItems
数组访问customView。
在我的例子中,要从 navigationItem 取回 customView:
let customView = navigationItem.rightBarButtonItems?.first?.customView // access the first
added customView
下面的代码成功地向 navigationItem
添加了一个 customView,但是当试图访问 customView
时它总是 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
}
结果:
nil
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)
这对我有用
我发现访问我们的 customView
(自定义 rightBarButtonItem
)的最佳方式,我们必须通过 Swift 标准方式访问:
添加customView后,我们只能通过self.navigationItem.rightBarButtonItems
数组访问customView。
在我的例子中,要从 navigationItem 取回 customView:
let customView = navigationItem.rightBarButtonItems?.first?.customView // access the first added customView