Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i create a navigationBar in UITableViewController in Swift?

Tags:

ios

swift

I am new to IOS,

I would like to add a UINavigationBar to UITableViewController, I have tried this:

var navBar: UINavigationBar = UINavigationBar(frame: CGRect(x:0, y:0, width:320, height:80))

then,

self.view .addSubview(navBar)

Thanks

like image 921
Tim Avatar asked Jul 10 '14 01:07

Tim


2 Answers

You can not simplly add a NavigationBar to UITableViewController like that.

The simplest way to have UINavigationController and NavigationBar is to do it from Storyboard.

Steps:-

  1. Drag the UITableViewController Object from Object Library to the Storyboard.

  2. Highlight the UITableViewController, go to Edit -> Embed In -> Navigation Controller like the screen shot below:- enter image description here

  3. Go to File -> New -> File.. -> iOS -> Cocoa Touch Class, and create a Custom TableViewController class like below screen shot:- enter image description here

  4. Finally, go back to storyboard and highlight the UITableViewController object. Under the identity inspector, choose the custom class that you have just created like the screen shot below:- enter image description here

You may do whatever you want with the custom class file. You may also add a custom UINavigationController class as well if you want and you may attach the custom class to to the object inside the storyboard.

like image 75
Ricky Avatar answered Oct 26 '22 10:10

Ricky


If this is merely the case of showing a modal UITableViewController with a navigation bar, the easiest way to do this from code is to present a UINavigationController with your UITableViewController as the rootViewController:

Presenting view controller:

let sourceSelectorTableViewController = SourceSelectorTableViewController()
let navigationController = UINavigationController(rootViewController: sourceSelectorTableViewController)

self.presentViewController(navigationController, animated: true, completion: nil)

Destination modal UITableViewController:

override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: "done")
    self.title = "Pick a Source"
}
func cancel() {
    self.dismissViewControllerAnimated(true, completion: nil)
}

func done() {
    //save things
    self.dismissViewControllerAnimated(true, completion: nil)
}
like image 33
Albert Bori Avatar answered Oct 26 '22 11:10

Albert Bori