简体   繁体   中英

iOS Storyboard: Not able to instantiate view controller properly

I'm really having trouble instantiating a custom view controller.

This is my storyboard set up. The third view controller is the one I'm trying to present.

I've tried both of these methods.

1: This results in black screen.

var searchController: SearchController = SearchController()
self.presentViewController(searchController, animated: true, completion: nil)

2: This results in a white, empty view controller popping up.

let mainStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let searchController : UIViewController = mainStoryboard.instantiateViewControllerWithIdentifier("searchController") as! UIViewController
self.presentViewController(searchController, animated: true, completion: nil)

Here is the code for the actual view controller:

class SearchController: UIViewController {

    lazy var searchBar: UISearchBar = UISearchBar(frame: CGRectMake(0, 0, 200, 20))

    override func viewDidLoad() {
        super.viewDidLoad()

        var leftItem = (UIBarButtonItem)(customView: searchBar)
        self.title = "Search"
        self.navigationItem.leftBarButtonItem = leftItem
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }    
}

It's very confusing because another custom view controller I am is presented properly while using method #1 above. Why wouldn't it work for this controller?

Thanks a lot everyone.

When using Storyboards you don't need to use presentViewController or instantiate your view controllers manually. Instead it's best to use a segue to move from one UIViewController to the next.

1. In your case, you want a show segue, which it looks like you've already done judging by your storyboard.

在此处输入图片说明

2. You need to give your segue an Identifier which you can do by selecting your segue and going to the Attributes Editor .

3. To perform your segue just call the following from your first view controller (instead of presentViewController ).

self.performSegueWithIdentifier("YourIdHere", sender: self)

This will cause the storyboard to instantiate your SearchViewController and present it in the way that you've defined for that segue.

4. If you want to pass any values to your SearchViewController , you can override prepareForSegue in UIViewController . In your first view controller:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let searchViewController = segue.destinationViewController where segue.identifier == "YourIdHere") {
        // Now you can set variables you have access to in `searchViewController`.
    }
}

And that should be it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM