Adding multiple custom bar buttons to custom nav b

2019-03-04 01:18发布

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)

    }

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?

3条回答
太酷不给撩
2楼-- · 2019-03-04 02:00

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]
}
查看更多
啃猪蹄的小仙女
3楼-- · 2019-03-04 02:02

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
查看更多
Lonely孤独者°
4楼-- · 2019-03-04 02:14

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.

查看更多
登录 后发表回答