Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding bar button items to nav bar without navigation controller in Swift [duplicate]

I'm trying to add multiple bar button items to each side of a custom nav bar.

I'm using the following method but nothing shows up.

There are a few threads on this in Obj-C but I'm struggling to translate the syntax. Is there a workaround for this in Swift?

@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)
    }
like image 273
slider Avatar asked Jul 09 '15 01:07

slider


1 Answers

If you are using a storyboard, drag a Navigation Bar, and drag a Navigation Item onto the navigation bar.

storyboard screenshot

Then connect an IBOutlet for your UINavigationitem

@IBOutlet weak var navItem: UINavigationItem!

override func viewDidLoad() {
    super.viewDidLoad()

    let navBarButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Bookmarks, target: self, action: nil)
    navItem.leftBarButtonItem = navBarButton
}

You can also use code:

let navbar = UINavigationBar(frame: CGRect(x: 0, y: 20,
    width: UIScreen.mainScreen().bounds.size.width, height: 50))
navbar.tintColor = .lightGray
self.view.addSubview(navbar)

let navItem = UINavigationItem(title: "Test")
let navBarButton = UIBarButtonItem(barButtonSystemItem: .bookmarks, target: self, action: nil)
navItem.leftBarButtonItem = navBarButton

navbar.items = [navItem]

nav bar screenshot

like image 93
Leo Avatar answered Oct 19 '22 09:10

Leo