我在viewDidLoad
中有以下内容。它设置自定义rightBarButtonItem
(在自定义UINavigationBar
中)。
let button = UIButton()
let attrs = [NSFontAttributeName: UIFont(name: "Montserrat-Light", size: 14)!, NSForegroundColorAttributeName: UIColor.black]
let title = NSAttributedString(string: "Sign In", attributes: attrs)
button.setAttributedTitle(title, for: .normal)
button.addTarget(self, action: #selector(self.pushVcLogin), for: .touchUpInside)
let parentView = UIView(frame: button.bounds)
parentView.addSubview(button)
button.sizeToFit()
parentView.bounds = CGRect(x: 0, y: 0, width: button.bounds.size.width, height: button.bounds.size.height)
self.navItem.rightBarButtonItem = UIBarButtonItem(customView: parentView)
定制的
UIBarButtonItem
看起来应该是这样,但它不可点击。有什么想法吗?
最佳答案
首先,如果视图层次结构具有UINavigationController
其次,您可以使用navigationItem并在其上添加自定义的uibarbuttonem。
我刚刚检查了下面的代码,它就工作了。
let button = UIButton()
let attrs = [NSFontAttributeName: UIFont(name: "Montserrat-Light", size: 14)!, NSForegroundColorAttributeName: UIColor.black]
let title = NSAttributedString(string: "Sign In", attributes: attrs)
button.setAttributedTitle(title, for: .normal)
button.addTarget(self, action: #selector(self.pushVcLogin), for: .touchUpInside)
let parentView = UIView(frame: button.bounds)
parentView.addSubview(button)
button.sizeToFit()
parentView.bounds = CGRect(x: 0, y: 0, width: button.bounds.size.width, height: button.bounds.size.height)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: parentView)
这里还有一个故事板图像navigationController和viewController的样子。
关于ios - UIBarButtonItem(customView :)-不可点击,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45344908/