将多个自定义栏按钮添加到自定义导航栏 [英] Adding multiple custom bar buttons to custom nav bar
问题描述
我需要在Swift的自定义导航栏的每一端添加两个小节按钮项。我正在使用以下方法,虽然我没有错误,但没有任何错误出现。我正在使用自己的自定义图标,当我使用界面构建器添加它们时会出现这些图标。显然,我只能在每一端添加一个。
I need to add two bar button items to each end of my custom navigation bar in Swift. I'm using the following method, and although I get no errors, nothing at all is appearing. I'm using my own custom icons, which do appear when I add them using interface builder. Obviously, I can only add one to each end that way.
@IBOutlet weak var navBar: UINavigationBar!
override func viewDidLoad() {
var iconOne = UIImage(named: "iconOne")
var iconTwo = UIImage(named: "iconTwo")
var buttonOne:UIBarButtonItem = UIBarButtonItem(image: iconOne, style: UIBarButtonItemStyle.Plain, target: self, action: nil)
var buttonTwo:UIBarButtonItem = UIBarButtonItem(image: iconTwo, style: UIBarButtonItemStyle.Plain, target: self, action: nil)
self.navBar.setItems([buttonOne,buttonTwo], animated: true)
}
这是在嵌入导航控制器的视图控制器中实现的。我可以使用 self.navigationItem.setRightBarButtonItems([buttonOne,buttonTwo],animated:true)
如果我没有使用自定义导航栏。什么是解决方法?
This is implemented in a view controller that's embedded in a navigation controller. I'd be able to use self.navigationItem.setRightBarButtonItems([buttonOne, buttonTwo], animated: true)
if I weren't using a custom nav bar. What's the workaround?
推荐答案
此代码适用于我:
@IBOutlet weak var navBar: UINavigationBar!
@IBOutlet weak var navBarItem: UINavigationItem!
func displayTextInNavBar(text: String) {
let labelWidth: CGFloat = navBar.frame.width / 6
let frame = CGRect(x: 0, y: 0, width: labelWidth, height: navBar.frame.height)
let label = UILabel(frame: frame)
label.textAlignment = .Right
label.textColor = UIColor(red: 0/255, green: 127/255, blue: 0/255, alpha: 1)
label.font = UIFont(name: "Bradley Hand", size: 20)
label.text = text
let navBarButtonItem = UIBarButtonItem(customView: label)
navBarItem.rightBarButtonItem = navBarButtonItem
}
上面的标签位于navBar的右侧。如果你想要一个可点击的实际按钮,请改为:
The above puts a label on the right side of the navBar. If you want an actual button that is clickable, do this instead:
let navBarButtonItem = UIBarButtonItem(title: text, style: .Plain, target: self, action: nil)
如果你希望该按钮在点击时实际执行某些操作,然后代替 nil
指定一些功能。
If you want that button to actually do something when clicked, then instead of nil
specify some function.
这篇关于将多个自定义栏按钮添加到自定义导航栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!