下面的代码成功地将一个customView添加到navigationItem
,但是当尝试访问customView
时,它总是返回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)
这对我有用