首页 > 代码库 > UINavigationController的简单总结

UINavigationController的简单总结

UINavigationController是IOS开发中常用的用于视图切换的控制器. 在对象管理上, UINavigationController采用stack的方式来管理各个view的层级, rootViewController在stack的最底层. 同时, 也提供了诸多方法用于进行view之间的切换及管理等.

常见的方法有pushViewController与popViewController等, 需要注意的是UINavigationController对应的segue的属性要设置为push方式.

看如下代码:

var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
    
    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
    self.window!.backgroundColor = UIColor.whiteColor()
    self.window!.makeKeyAndVisible()
    
    //RootTableViewController为自己定义的一个管理tableView的controller
    var root = RootTableViewController()
    var navCtrl = UINavigationController(rootViewController: root)
    //指定将该RootTableViewController放在栈底。
    self.window!.rootViewController = navCtrl
    return true
}
其中, self.window!.rootViewController = navCtrl即指定了当前的rootViewController.


下面, 创建一个WebView并push到UINavigationController的管理视图中:

    //点击tableView中的一个cell调用的方法
    override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!){
        //indexPath即代表了所点击的cell那一行
        var row=indexPath.row as Int
        var data=http://www.mamicode.com/self.dataSource[row] as XHNewsItem>上边代码执行的效果即为, 点击tableView中的一个cell, 会新创建一个WebViewController并将其压入UINavigationController的view栈中.

则UI上呈现出来的就是该WebView的内容. 同时, 导航栏上会自动呈现相应的返回按钮, 点击则会完成将该WebView出栈的操作, 进而回退到之前的tableView中.

而回退的操作即会调用popViewController方法.


针对UINavigationController, 也可以采用storyboard的方式添加. 步骤如下:

1, 选中一个viewController, 然后Editor->Embed in>Navigation Controller, 就可以将该viewController设为该UINavigationController的最底层view.

2, 在storyboard中选中tableView中的table view cell, 右键连线至要跳转的视图WebView. 设置segue的Identifier及push模式. 如图:

技术分享

技术分享

3, 然后在didSelectRowAtIndexPath可以通过调用performSegueWithIdentifier()方法来触发segue的动作, 以完成view的切换操作. 代码如下:

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        var data = http://www.mamicode.com/dataSource[indexPath.row] as NewsItem>在两个视图之间传递数据是通过重写prepareForSegue方法来实现的.

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "web" {
            var vc = segue.destinationViewController as WebViewController
            vc.newsId = selectedUrl! // 则在webViewController中就可以使用newsId这个变量了
        }
    }

我们会发现, 使用storyboard会非常的方法, 也是最不易出错的. 但通过代码方式添加UINavigationController的方法可能在某些特定场景下非常实用的.

大家都可以多试一试.

最后, 需要记住的是 UINavigationController是采用类似stack的push和pop的方式完成view的切换, 调用方法为pushViewController和popViewController.

而UITabBarController是平级view之间的切换, 调用方法为presentViewController和dismissViewController.




UINavigationController的简单总结