我在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
看起来应该如此,但它不可用。
有什么想法吗?
答案 0 :(得分:1)
首先,如果您的视图层次结构具有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)
这里也是故事板图像,navController和viewController的外观如何。