问题
I have 6 to 7 viewControllers in my storyBoard and in this view controller I get self.navigationController as nil but works every where else . I've done the same thing every other place but this one doesn't work. I couldn't figure out why? import UIKit
class wkScreen2ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// tableView.estimatedRowHeight = 500
tableView.rowHeight = UITableViewAutomaticDimension
// tableView.scrollEnabled = true
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return 3
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->
UITableViewCell {
if(indexPath.row == 0){
var cell: Cell1TableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell1") as Cell1TableViewCell
return cell
}
if(indexPath.row == 1){
println("2")
var cell: Cell2TableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell2") as Cell2TableViewCell
return cell
}
if(indexPath.row == 2){
println("3")
var cell: Cell3TableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell3") as Cell3TableViewCell
return cell
}
return UITableViewCell()
}
func navigateTowkScreen3(){
println("next2")
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var wkScr3 = mainStoryboard.instantiateViewControllerWithIdentifier("wkScreen3") as wkScreen3ViewController
println(wkScr3)
println(self.navigationController)
self.navigationController?.pushViewController(wkScr3, animated: true)
}
}
https://www.dropbox.com/s/0q7whsgiq3nw14e/Screen%20Shot%202014-12-10%20at%203.39.06%20PM.png?dl=0
回答1:
The easiest way to fix this is to use a segue.
You said you wanted to check on a condition when the next button is pressed before actually going to the next screen though.
So, you first need to add the segue. But instead of adding it from the Next button to the view controller you need to add it from the first view controller (little yellow box) to the second view controller.
Like this...
Then give the segue an identifier like WalkThrough1Segue.
Now if your code you will have your next button function like this...
func navigateTowkScreen3() {
// first check your condition
if (/*some condition*/) {
// trigger the segue
performSegueWithIdentifier("WalkThrough1Segue")
}
}
来源:https://stackoverflow.com/questions/27406699/self-navigationcontroller-is-nil-in-swift