我在 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
看起来应该是这样,但它不可点击。
有什么想法吗?
最佳答案
首先,如果您的 View 层次结构具有 UINavigationController
其次,您可以使用 navigationItem 并在其上添加自定义 UIBarButtonItem。
我刚刚检查了以下代码,它有效。
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 的 Storyboard图像。
关于ios - UIBarButtonItem(自定义 View :) -- not tappable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45344908/