Adding multiple custom bar buttons to custom nav bar

那年仲夏 提交于 2019-12-02 11:09:12

This code works for me:

@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
}

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)

If you want that button to actually do something when clicked, then instead of nil specify some function.

My solution to do it:

var barButton : UIBarButtonItem?

override func viewDidLoad() {
    self.barButton = UIBarButtonItem(title: "Options", style: .plain, target: self, action: nil))
    self.navigationItem.rightBarButtonItems = [barButton] as? [UIBarButtonItem]
}

UIBarButtonItem can be created with an custom view

  • create a view
  • add UIButtons to it
  • layout it
  • create a UIBarButtonItem with custom view
  • add it to the navigation bar
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!