(本文代码已升级至Swift5)
故事板(UIStoryboard)可以很方便的进行界面的设计,下面总结了常用的几个操作方法:
1、初始场景
选中 View Controller,在属性面板里勾选 Is Initial View Controller 复选框,即可设置为起始场景(前面会显示灰色的小箭头)
2、添加 segue
使用 seque 的好处是,页面的切换不再需要创建任何代码。按住 Ctrl 键同时拖动控件到目标场景,在弹出的上下文菜单中选择 segue 类型。
(1)菜单中最下面两个是过去版本的使用方式,推荐最上面的4个新的方式:
- Show:就是Push一个新的视图
- Show Detail:替换当前的视图方式来展现新的视图
- Present Modally:模式窗口的方式
- Present As Popover:浮窗形式
-
Cutom:自定义形式
image.png
(2)两个 Controller 之间也是可以建立关联的,方法同上。
3、给 segue 添加关联类
在 stroyboard 中添加一个 segue 时并不会同步添加对应的类。如果需要,我们要手动先创建一个 swift 类,比如叫 MyView1。然后进入 storyboard,选中对应的 segue。在属性面板中设置对应的 Class,如下图:
image.png
4、添加代码关联
(1)打开 Assistant Editor 同时显示界面设计与代码,按住 Ctrl 键同时拖动控件到代码,在弹出的上下文菜单中设置需要关联的类型,即可在代码里自动生成代码。
(2)这里主要有两种关联类型:
- 一种是 Outlet 连接,就是在代码里创建界面元素的成员变量引用。
- 另一种是 Action 事件,把界面元素的响应事件方法添加到代码里来。
(如果已经创建了代码,也可以把控件直接拖放到对应代码上,这时候就不是插入而是直接建立连接了)
5、同一个 storyboard 里多个 View Controller 的引用
如果要在代码里调用 storyboard 里的 View Controller,可以设置 View Controller 的 identity。设置方法是,在 stroyboard 中选中 View Controller,在右侧的 identity 属性面板里设置 Stroyboard ID。
比如设置类 Main.storyboard 里初始 View Controller 的 identity 为 RootView,则通过以下方式引用:
var rootViewController = UIStoryboard(name: "Main", bundle: nil)
.instantiateViewController(withIdentifier: "RootView") as UIViewController
对于初始 View Controller 也可以不通过 identity 直接获取:
var rootViewController = UIStoryboard(name: "Main", bundle: nil)
.instantiateInitialViewController()
6、使用多个 storyboard 文件
一个项目可以不止一个 storyboard 文件,它们间也可以互相调用。假如还添加一个 Second.storyboard,里面的 View Controller 设置 identity 为 SecondView,则我们可以通过导航的方式来关联两个 storyboard 文件。
(1)在 AppDelegate 的 Application 入口里把Main面板放入导航控制:
let rootViewController = UIStoryboard(name: "Main", bundle: nil)
.instantiateInitialViewController()!
self.window!.rootViewController = UINavigationController(rootViewController:
rootViewController)
(2)然后可以在 RootView 里放入一个按钮,点击事件里导航到 Second 面板:
let viewController = UIStoryboard(name: "Second", bundle: nil)
.instantiateViewController(withIdentifier: "SecondView") as UIViewController
self.navigationController?.pushViewController(viewController, animated: true)
原文出自:www.hangge.com 转载请保留原文链接:https://www.hangge.com/blog/cache/detail_635.html
网友评论