实现iOS同一个页面present两个页面
一、整体流程
在iOS开发中,要实现同一个页面同时present两个页面,可以通过以下步骤来操作:
步骤 | 操作 |
---|---|
1 | 创建一个父控制器,用于展示两个子控制器的内容 |
2 | 创建两个子控制器,分别用于展示不同的内容 |
3 | 在父控制器中添加两个按钮,点击按钮时分别present两个子控制器 |
二、具体步骤
1. 创建父控制器
首先,在父控制器中添加两个按钮,用于分别present两个子控制器。
// 创建父控制器
class ParentViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button1 = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
button1.setTitle("Present VC1", for: .normal)
button1.addTarget(self, action: #selector(presentVC1), for: .touchUpInside)
self.view.addSubview(button1)
let button2 = UIButton(frame: CGRect(x: 100, y: 200, width: 100, height: 50))
button2.setTitle("Present VC2", for: .normal)
button2.addTarget(self, action: #selector(presentVC2), for: .touchUpInside)
self.view.addSubview(button2)
}
@objc func presentVC1() {
let vc1 = ChildViewController1()
present(vc1, animated: true, completion: nil)
}
@objc func presentVC2() {
let vc2 = ChildViewController2()
present(vc2, animated: true, completion: nil)
}
}
2. 创建子控制器
分别创建两个子控制器,用于展示不同的内容。
// 创建子控制器1
class ChildViewController1: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 添加子控制器1的视图和内容
}
}
// 创建子控制器2
class ChildViewController2: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 添加子控制器2的视图和内容
}
}
3. 在AppDelegate中设置初始显示的页面为父控制器
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = ParentViewController()
window?.makeKeyAndVisible()
return true
}
三、类图
classDiagram
class ParentViewController {
viewDidLoad()
+ presentVC1()
+ presentVC2()
}
class ChildViewController1 {
viewDidLoad()
}
class ChildViewController2 {
viewDidLoad()
}
四、序列图
sequenceDiagram
participant ParentViewController
participant ChildViewController1
participant ChildViewController2
ParentViewController->>ChildViewController1: presentVC1()
ChildViewController1->>ParentViewController: Return
ParentViewController->>ChildViewController2: presentVC2()
ChildViewController2->>ParentViewController: Return
通过以上步骤和代码,你可以实现iOS同一个页面present两个页面的效果。希望对你有帮助!