swiftswift2uinavigationbaruinavigationitemuibuttonbaritem

How add button on NavigationBar dynamically (in runtime)? - Swift 2.0


I'm trying to add navigation bar dynamically, but something a little strange is happening.

My Screen is just a UINavigation and a View with red background:

enter image description here

And this is my Swift code:

import UIKit

class ViewController: UIViewController {

    @IBOutlet var navBar: UINavigationBar!

    @IBOutlet var viewLongPress: UIView!

    var viewLongPressInitialPosition: CGPoint!

    var frameSize: CGSize {
        get {
            return self.view.frame.size
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        navBar.frame.size.height = 64.0

        viewLongPress.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: "viewLongPressAction:"))

        viewLongPressInitialPosition = viewLongPress.frame.origin
    }

    func viewLongPressAction(sender: UILongPressGestureRecognizer) {

        let locationInView = sender.locationInView(self.view)

        if sender.state == .Began {

        } else if sender.state == .Changed {

            viewLongPress.frame.origin = CGPoint(x: locationInView.x - (viewLongPress.frame.width / 2), y: locationInView.y - (viewLongPress.frame.height / 2))

        } else if sender.state == .Ended {

            if locationInView.y <= navBar.frame.height {

                let item = UINavigationItem()
                item.rightBarButtonItems = [UIBarButtonItem(title: "Test", style: .Plain, target: nil, action: "noAction:")]

                navBar.items?.append(item)

            }

            viewLongPress.frame.origin = viewLongPressInitialPosition
        }
    }

    func noAction(sender: AnyObject) {

    }
}

I'm trying to add a UINavigationItem to finish dragging the view on top of the navigation bar.

But when I add the button, the navigation bar looks like this:

enter image description here

The button should be added and look like this:

enter image description here

I think I'm missing something, but I can not solve.


I tried to add a second button (leftBar), but the title disappeared.

And if you already have a button, how do I add one more button?


Can someone help me?

Thanks for the answer.


Solution

  • You're replacing your whole UINavigationItem which is probably not what you want. Try self.navigationItem.rightBarButtonItem = ... instead. You don't even have to interact with the actual navigation bar, just the current view controller's navigation item (which aslo contains its title).

    Edit: it looks like your navBar already has a navigation item. What happens if you do this assignment instead: self.navBar.items.first?.rightBarButtonItem = ...