Swift 3.0 Adding a Right Button to Navigation Bar

Viewed 62344

I have added a navigation bar to the top of a view controller. I am trying to control whether a button is visible based a condition, but I am having trouble adding the button. So far I have,

var addButton: UIBarButtonItem = UIBarButtonItem(title: "test", style: .done, target: self, action: #selector(addTapped))

override func viewDidLoad() {
    super.viewDidLoad()

    let boool = true
    if boool {
        self.navigationItem.rightBarButtonItem = self.addButton
    }
    else {
        self.navigationItem.rightBarButtonItem = nil
    }
}

func addTapped(sender: AnyObject) {
    print("hjxdbsdhjbv")
}

I believe it is not working properly because I have added a navigation bar into the VC, instead of using a navigation controller and working with the bar there. I was wondering if there was a way to work with this navigation bar.

6 Answers
let rightBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "EditImage"), style: .done, target: self, action: #selector(ViewController.call_Method))

self.navigationItem.rightBarButtonItem = rightBarButtonItem

Swift 4.2;

Add viewController

override func viewDidLoad() {
        super.viewDidLoad()
        self.addNavigationBarButton(imageName: "ic_back", direction:.left)
 }

Add Class your API or Utility Class

public func addNavigationBarButton(imageName:String,direction:direction){
    var image = UIImage(named: imageName)
    image = image?.withRenderingMode(.alwaysOriginal)
    switch direction {
    case .left:
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style:.plain, target: nil, action: #selector(goBack))
    case .right:
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style:.plain, target: nil, action: #selector(goBack))
    }
}

@objc public func goBack() {
    self.navigationController?.popViewController(animated: true)
}

public enum direction {
    case right
    case left
}

tested in Xcode 10.2, swift 5.0; First, I have have embedded my ViewController in UINavigationController in IB. Then in ViewDidLoad include these lines

self.title = "orange"
 self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(changeLayout)).

Note - accessing title, or adding button through navigation controller did not work. For example : setting title - Self.navigationcontroller.navigationItem.title did not work ,

Related