iOS Storyboard:无法正确实例化视图控制器

时间:2015-04-10 01:31:00

标签: ios swift uiviewcontroller storyboard

我在实例化自定义视图控制器时遇到了麻烦。

This是我的故事板设置。第三个视图控制器是我试图呈现的那个。

我尝试了这两种方法。

1:这会导致黑屏。

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

2:这会导致弹出一个白色的空视图控制器。

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

以下是实际视图控制器的代码:

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()
    }    
}

这非常令人困惑,因为我使用另一个自定义视图控制器时使用上面的方法#1。为什么它对这个控制器不起作用?

非常感谢大家。

1 个答案:

答案 0 :(得分:2)

使用Storyboard时,您无需使用presentViewController或手动实例化视图控制器。相反,最好使用segue从一个UIViewController移动到下一个。{/ p>

1。在您的情况下,您需要一个 show segue,看起来您已经完成了故事板评判。

enter image description here

2。您需要为segue指定一个Identifier,您可以选择segue并转到属性编辑器

3。要执行您的segue,只需从第一个视图控制器(而不是presentViewController)调用以下内容。

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

这将导致故事板实例化您的SearchViewController,并以您为该segue定义的方式呈现它。

4. 如果您想将任何值传递给SearchViewController,可以覆盖prepareForSegue中的UIViewController。在您的第一个视图控制器中:

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`.
    }
}

那应该是它!

相关问题