通过使用导航条(UINavigationBar)与导航条控制器(UINavigationController)可以方便的在主页面和多层子页面之间切换。下面通过一个简单“组件效果演示”的小例子来说明如何通过代码来进行页面的切换。

功能如下:
1,在AppDelagete.swift入口文件中把首页ViewController做了导航控件的封装
2,首页是一个表格列出几个Swift控件的名称
3,点击表格项即切换到对应组件展示页面,顶部的导航条标题变为该控件的名称,同时导航条左侧还有返回按钮
4,在展示页中,给导航条右侧添加了“效果/代码”切换的按钮,点击分别展示组件的效果和代码
效果图如下:
     
代码如下:
--- 入口文件 AppDelegate.swift ---
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import UIKit
 
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
                             
    var window: UIWindow?
 
    func application(application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        // Override point for customization after application launch.
         
        // 把起始ViewController作为导航控件封装,我们在ViewController里就能调用导航条进行页面切换了
        var rootViewController = ViewController()
        var rootNavigationController = UINavigationController(rootViewController: rootViewController)
        self.window!.rootViewController = rootNavigationController
         
        return true
    }
 
    func applicationWillResignActive(application: UIApplication) {
    }
 
    func applicationDidEnterBackground(application: UIApplication) {
    }
 
    func applicationWillEnterForeground(application: UIApplication) {
    }
 
    func applicationDidBecomeActive(application: UIApplication) {
    }
 
    func applicationWillTerminate(application: UIApplication) {
    }
}
--- 主页面 ViewController.swift ---
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import UIKit
 
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
     
    // 表格加载
    var tableView:UITableView?
     
    // 控件类型
    var ctrls = ["UILabel", "UIButton", "UIImageView", "UISlider", "UIWebView"]
                             
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
         
        self.title = "Swift控件演示"
        self.tableView = UITableView(frame:self.view.frame, style:UITableViewStyle.Plain)
        self.tableView!.delegate = self
        self.tableView!.dataSource = self
        self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "SwiftCell")
        self.view.addSubview(self.tableView!)
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
     
    // UITableViewDataSource协议方法
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return self.ctrls.count
    }
     
    // UITableViewDataSource协议方法
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
        -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCellWithIdentifier("SwiftCell", forIndexPath:indexPath)
            as UITableViewCell
        cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
        cell.textLabel?.text = self.ctrls[indexPath.row]
         
        return cell
    }
     
    // UITableViewDelegate协议方法,点击时调用
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath!)
    {
        // 跳转到detailViewController,取消选中状态
        self.tableView!.deselectRowAtIndexPath(indexPath, animated: true)
        // 创建DetailViewController
        var detailViewController = DetailViewController()
        // 传递控件的title,在detailView里用于判断生成响应的控件
        detailViewController.title = self.ctrls[indexPath.row]
        // navigationController跳转到detailViewController
        self.navigationController!.pushViewController(detailViewController, animated:true)
    }
}
--- 子页面 DetailViewController.swift ---
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import UIKit
 
class DetailViewController: UIViewController {
     
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
         
        //设置背景色
        self.view.backgroundColor = UIColor.whiteColor()
        //按title加载控件
        loadControl(self.title!)
         
        //设置代码和控件展示切换按钮,增加到导航条的右侧
        //这里采用了navigationController不能增加navigationItem
        let btn = UIBarButtonItem(title:"代码", style: UIBarButtonItemStyle.Bordered,
            target: self, action: "btnCodeClicked:")
        self.navigationItem.rightBarButtonItem = btn
    }
     
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
     
    //构建控件并加载到界面
    func loadControl(ctrl:String) {
        switch (ctrl) {
        case "UILabel":
            let label = UILabel(frame: self.view.bounds)
            label.backgroundColor = UIColor.clearColor()
            label.textAlignment = NSTextAlignment.Center
            label.font = UIFont.systemFontOfSize(36)
            label.text = "Hello, Ucai"
            self.view.addSubview(label)
        case "UIButton":
            var button = UIButton(frame: CGRectMake(110,120,100,60))
            button.backgroundColor = UIColor.blueColor()
            button.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
            button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)
            button.setTitle("点击我", forState: .Normal)
            button.addTarget(self, action: "buttonClicked:",
                forControlEvents: UIControlEvents.TouchUpInside)
            self.view.addSubview(button)
        case "UIImageView":
            var image     = UIImage(named: "swift.png")
            var imageView = UIImageView(frame:
                CGRectMake((CGRectGetWidth(self.view.bounds) - image!.size.width) / 2.0, 120.0,
                    image!.size.width, image!.size.height))
            imageView.image = image!
            self.view.addSubview(imageView)
        case "UISlider":
            let slider = UISlider(frame:CGRectMake(60.0, 120.0, 200.0, 30.0))
            self.view.addSubview(slider)
        case "UIWebView":
            var webView = UIWebView(frame:self.view.bounds)
            var url = NSURL(string: "http://hangge.com")
            var request = NSURLRequest(URL: url!)
            webView.loadRequest(request)
            self.view.addSubview(webView)
         
        default:
            println("control name: \(ctrl)")
        }
    }
     
    //显示控件的代码
    func loadCode(ctrl:String) {
        var str:String
        switch (ctrl) {
        case "UILabel":
            str = "let label = UILabel(frame: self.view.bounds)\n"
            str += "label.backgroundColor = UIColor.clearColor()\n"
            str += "label.textAlignment = NSTextAlignment.Center\n"
            str += "label.font = UIFont.systemFontOfSize(36)\n"
            str += "label.text = \"Hello, Ucai\"\n"
            str += "self.view.addSubview(label)"
        case "UIButton":
            str = "UIButton"
        case "UISlider":
            str = "let slider = UISlider(frame:CGRectMake(60.0, 120.0, 200.0, 30.0))\n"
            str += "self.view.addSubview(slider)"
        default:
            str = "other ctrl"
        }
         
        //在导航条下方位置显示源代码
        var txt = UITextView(
            frame: CGRectMake(0, 60, self.view.bounds.size.width, self.view.bounds.size.height - 60))
        txt.text = str
        self.view.addSubview(txt)
    }
    //清空所有子视图
    func clearViews() {
        for v in self.view.subviews as [UIView] {
            v.removeFromSuperview()
        }
    }
     
    func buttonClicked(sender:AnyObject) {
        println("you clicked button")
    }
     
    //显示控件的代码
    func btnCodeClicked(sender:AnyObject) {
        println("title: \(self.title)")
        clearViews()
        if self.navigationItem.rightBarButtonItem!.title == "代码" {
            loadCode(self.title!)
            self.navigationItem.rightBarButtonItem!.title = "效果"
        }
        else {
            self.navigationItem.rightBarButtonItem!.title = "代码"
            loadControl(self.title!)
        }
    }
    /*
    func btnBackClicked(sender:AnyObject) {
        self.navigationController.navigationBar.popNavigationItemAnimated(true)
    }
    */
}

如果使用StoryBoard实现更加简单

AppDelegate.swift都不需要修改。打开Main.storyboard。

(1)点击首页的Scene,选择Editor -> Embed In -> Navigation Controller 即可。
(2)从首页单元格拖“show”的关联Segue到详细页,或从首页View Controller拖手动关联Segue到详细页,并定义这个Segue的Indentifier(比如detail)
这样,点击单元格跳转的代码有所改变,是根据刚才定义Segue的Indentifier来跳转
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// UITableViewDelegate协议方法,点击时调用
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath!)
{
    // 跳转到detailViewController,取消选中状态
    self.tableView!.deselectRowAtIndexPath(indexPath, animated: true)
    //更具定义的Segue Indentifier进行跳转
    self.performSegueWithIdentifier("detail", sender: self.ctrls[indexPath.row])
}
     
//在这个方法中给新页面传递参数
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "detail"{
        let controller = segue.destinationViewController as! DetailViewController
        controller.title = sender as? String
    }
}

Swift - 使用导航条和导航条控制器来进行页面切换的更多相关文章

  1. [Swift通天遁地]九、拔剑吧-(8)创建气泡式页面切换效果

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...

  2. Swift - 使用导航条和导航条控制器来进行页面切换并传递数据

    转自:http://www.hangge.com/blog/cache/detail_586.html

  3. 控制器隐藏了导航 下页pop 导航位置看到黑条

    控制器隐藏了导航 下页pop 导航位置看到黑条 解决: -(void)viewWillDisappear:(BOOL)animated{        [super viewWillDisappear ...

  4. iOS WKWebView 加载进度条、导航栏返回&关闭 (Swift 4)

    导航: 1.加载进度条 2.导航栏增加返回.关闭按钮 加载进度条 效果图 代码如下: self.progressView.trackTintColor = UIColor.white self.pro ...

  5. iOS:导航栏的工具条和导航条

    功能:用NAV视图控制器打开新的视图,默认工具条和导航条隐藏,双击显示之 // // main.m // Hello // // Created by lishujun on 14-8-28. // ...

  6. Bootstrap如何实现导航条?导航条实例详解

    本文主要和大家分享Bootstrap实现导航实例详解,在建设一个网站的时候,不同的页面有很多元素是一样的,比如导航条.侧边栏等,我们可以使用模板的继承,避免重复编写html代码.现在我们打算实现一个在 ...

  7. Bootstrap学习-导航条-分页导航

    1.导航条基础 导航条(navbar)和上一节介绍的导航(nav),就相差一个字,多了一个“条”字.其实在Bootstrap框架中他们还是明显的区别.在导航条(navbar)中有一个背景色.而且导航条 ...

  8. 15 Flutter BottomNavigationBar自定义底部导航条 以及实现页面切换 以及模块化

    效果: /**  * Flutter  BottomNavigationBar 自定义底部导航条.以及实现页面切换:  * BottomNavigationBar是底部导航条,可以让我们定义底部Tab ...

  9. ios swift 实现饼状图进度条,swift环形进度条

    ios swift 实现饼状图进度条 // // ProgressControl.swift // L02MyProgressControl // // Created by plter on 7/2 ...

随机推荐

  1. 如何创建C++程序

    下载Microsoft Visual C++ 6.0请点击这里:VC 6.0下载(包括中文版英文版)(支持Win7和XP) 首先,我们要进入Microsoft Visual C++集成开发环境(Int ...

  2. 工作随记 warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds

    错误信息:F:\BUILD\IDS7020\trunk\manage_src\dev\java_src\tds7030-web\Ant\build.xml:344: warning: 'include ...

  3. IOS SWIFT 简单操作文件

    //Home目录 let homeDirectory = NSHomeDirectory() //Documents目录 苹果建议将程序中建立的或在程序中浏览到的文件数据保存在该目录下,iTunes备 ...

  4. export和import实现模块化

    export和import实现模块化 阅读目录 ES6的模块化的基本规则或特点: 下面列出几种import和export的基本语法: ES6导入的模块都是属于引用: 循环依赖的问题: 浏览器兼容: 参 ...

  5. Qt 内存管理机制

    这篇文章首先发布于我的主页 http://www.devbean.info,以后也会直接发布在那里.现在有 Flex 4 的一篇和 <从 C++ 到 Objective-C>系列,感谢大家 ...

  6. HEVC码率控制浅析——HM代码阅读之一

    HM的码率控制提案主要参考如下三篇:K0103,M0036,M0257.本文及后续文章将基于HM12.0进行讨论,且首先仅讨论K0103对应的代码,之后再陆续补充M0036,M0257对应的代码分析, ...

  7. mysql 初识之日志文件篇

    日志文件 1. err日志     error log 记录mysql在运行的过程中所有较为严重的警告和错误信息,以及mysql server每次启动和关闭的详细信息.系统在默认情况下关闭error ...

  8. PHP - 类库

    常用的PHP类库,PHP开发者必备[转] PHP开发者常用的PHP类库和组件 PDF 生成器 FPDF - 这量一个可以让你生成PDF的纯PHP类库. Excel 相关 你的站点需要生成Excel?没 ...

  9. 工作线程AfxBeginThread的使用

    工作线程通常用来执行一些后台任务,如:数据计算.后台杀毒等等.因为不需要创建窗口和处理用户消息,编写比较容易,在程序中只要调用AfxBeginThread 函数就可以创建并启动一个工作线程了. Afx ...

  10. python算法之二分查找

    说明:大部分代码是在网上找到的,好几个代码思路总结出来的 通常写算法,习惯用C语言写,显得思路清晰.可是假设一旦把思路确定下来,并且又不想打草稿.想高速写下来看看效果,还是python写的比較快.也看 ...