前言
IOS应用跳转页面
通过代码的方式跳转页面
创建一个新的视图类
- 创建一个新的视图文件
ViewControllerNew.swift
- 创建一个
ViewController
类,继承自UIViewController
类
- 在这个
ViewController
类中添加一个Label对象
ViewControllerNew.swift1 2 3 4 5 6 7 8 9
| import UIKit
class ViewControllerNew: UIViewController {
override func viewDidLoad() { super.viewDidLoad() }
}
|
通过storyboard创建 View Controller 组件并关联新的视图类
Main.storyboard
->+
->添加一个View Controller
组件到页面中
- 选中ViewController->
Show the Identity inspector
->关联新的视图类
向新的组件中添加其他组件
在新的视图类中实例化其他组件对象
- 在
ViewControllerNew
类中创建一个Label组件
x
、y
:指定组件位于左上角原点的坐标
width
、height
:指定组件的宽高
ViewControllerNew.swift1 2 3 4
| let label = UILabel() label.text = "文本内容" label.frame = CGRect(x: 0, y: 0, width: 100, height: 100) view.addSubview(label)
|
在旧的视图类中跳转到新的视图
animated
:是否显示动画
completion
:关闭新的视图后执行的函数
ViewControllerOld.swift1 2 3
| let view2 = ViewControllerNew()
self.present(view2, animated: true, completion: nil)
|
传递参数
在新的视图类中定义属性
ViewControllerNew.swift1 2 3 4 5 6 7 8 9 10 11
| import UIKit
class ViewControllerNew: UIViewController {
var name = ""
override func viewDidLoad() { super.viewDidLoad() }
}
|
在旧的视图类中实例化新的视图对象时设置属性
ViewControllerOld.swift1 2 3 4
| let view2 = ViewControllerNew() view2.name = ""
self.present(view2, animated: true, completion: nil)
|
在新的视图类中使用属性值
ViewControllerNew.swift1 2 3 4 5 6 7 8 9 10 11 12
| import UIKit
class ViewControllerNew: UIViewController {
var name = ""
override func viewDidLoad() { super.viewDidLoad() print(name) }
}
|
通过Segue的方式创建跳转页面
创建 Cocoa Touch Class 作为新的视图类
- 定义类名->定义父类为
UIViewController
通过storyboard创建新的 View Controller 组件并关联跳转动作
Main.storyboard
->+
->添加一个View Controller
组件到页面中
- 按住
Control
键,从View Controller
拖拽到View Controller2
- 选中连接关系->定义
Identifier
内容作为标记
向新的视图组件中添加其他组件
在新的视图类中实例化其他组件对象
- 在
ViewControllerNew
类中创建一个Label组件
x
、y
:指定组件位于左上角原点的坐标
width
、height
:指定组件的宽高
ViewControllerNew.swift1 2 3 4
| let label = UILabel() label.text = "文本内容" label.frame = CGRect(x: 0, y: 0, width: 100, height: 100) view.addSubview(label)
|
在旧的视图类中跳转到新的视图
withIdentifier
:定义连接关系的Identifier
内容
sender
:定义跳转的发起者
ViewControllerOld.swift1
| self.performSegue(withIdentifier: "name", sender: self)
|
传递参数
在新的视图类中定义属性
ViewControllerNew.swift1 2 3 4 5 6 7 8 9 10 11
| import UIKit
class ViewControllerNew: UIViewController {
var name = ""
override func viewDidLoad() { super.viewDidLoad() }
}
|
在旧的视图类中重写prepare()方法并传递参数
ViewControllerOld.swift1 2 3 4 5 6
| override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "name" { let destinationViewController = segue.destination as! ViewControllerNew destinationViewController.name = "" } }
|
在新的视图类中使用属性值
ViewControllerNew.swift1 2 3 4 5 6 7 8 9 10 11 12
| import UIKit
class ViewControllerNew: UIViewController {
var name = ""
override func viewDidLoad() { super.viewDidLoad() print(name) }
}
|
在新的视图返回到旧的视图
ViewControllerNew.swift1
| self.dismiss(animated: true, completion: nil)
|
完成
参考文献
哔哩哔哩——疯狂滴小黑