navigationItem.leftBarButton is not appearing (Xcode Swift 4 IOS)

I have made a UITableViewController(iOS controller for table views) and attempted to put a logout button in the top left corner of the screen with this code:

class ViewController: UITableViewController {

var logoutButton : UIBarButtonItem!

override func viewDidLoad() {
    super.viewDidLoad()

    logoutButton = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(handleLogout))
    navigationItem.leftBarButtonItem = logoutButton

}

The iOS simulator just shows an empty (white) table view. I thought this would be a pretty simple task and have no idea why its not working or where to go from here. Any help would be appreciated.

Update: I have also tried to add navigation buttons to UINavigationController and UIViewController; the code looks like this

class ViewController: UINavigationController {

override func viewDidLoad() {
    super.viewDidLoad()

    let logoutButton = UIBarButtonItem(title: "Logout", style: .plain, target: nil, action: nil)
    navigationItem.leftBarButtonItem = logoutButton
}


class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    let logoutButton = UIBarButtonItem(title: "Logout", style: .plain, target: nil, action: nil)
    navigationItem.leftBarButtonItem = logoutButton
}

My AppDelegate looks like this:

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    window = UIWindow(frame: UIScreen.main.bounds)
    window?.rootViewController = ViewController()
    window?.makeKeyAndVisible()
    return true
}

Nothing works. I cannot get a button to display. I don't want to use storyboards but I'm left with few other options if I can't even get a button to load. Any help is appreciated. Thanks!

2 answers

  • answered 2018-11-08 07:59 Tapiwanashe Shoshore

    in this case you are have to push a loginViewController again at a logout time instead you need to popToRootViewControllerAnimated code use this code on your logout button clickEvnet:

    [self.navigationController popToRootViewControllerAnimated:YES];
    

    if you are using swift then use this code

    self.navigationController?.popToRootViewControllerAnimated(true)
    

  • answered 2018-11-09 00:45 Tony Hunt

    The problem was in the appDelegate. The rootViewController should have been set like:

    window?.rootViewController = UINavigationViewController(rootViewController: UITableViewController())
    

    As opposed to:

    window?.rootViewController = UITableViewController()
    

    I think this is what the comments were trying to point out; thanks!