iOS页面间通信方案全面解析
在iOS应用开发中,页面(ViewController)间的数据传递和通信是核心功能之一。根据不同的场景和需求,iOS提供了多种通信方案,每种方案都有其适用场景和优缺点。
一、基础通信方案
1. 属性直接传递(正向传值)
适用场景:A页面跳转到B页面时传递数据
// 在A页面(源页面)
let bVC = BViewController()
bVC.data = "要传递的数据" // 直接设置属性
bVC.user = User(name: "张三")
self.navigationController?.pushViewController(bVC, animated: true)
// 在B页面(目标页面)
class BViewController: UIViewController {
var data: String?
var user: User?
override func viewDidLoad() {
super.viewDidLoad()
print("接收到的数据: \(data ?? "")")
print("用户: \(user?.name ?? "")")
}
}
2. 代理模式(Delegate,反向传值)
适用场景:B页面返回A页面时回调数据
// 1. 定义协议
protocol BViewControllerDelegate: AnyObject {
func didSelectItem(_ item: String)
}
// 2. 在B页面
class BViewController: UIViewController {
weak var delegate: BViewControllerDelegate?
@IBAction func confirmButtonTapped() {
delegate?.didSelectItem("返回的数据")
navigationController?.popViewController(animated: true)
}
}
// 3. 在A页面
class AViewController: UIViewController, BViewControllerDelegate {
func openBPage() {
let bVC = BViewController()
bVC.delegate = self
navigationController?.pushViewController(bVC, animated: true)
}
// 实现代理方法
func didSelectItem(_ item: String) {
print("接收到返回数据: \(item)")
}
}
3. 闭包回调(Closure,反向传值)
适用场景:简单回调场景,替代代理模式
// 在B页面
class BViewController: UIViewController {
var completionHandler: ((String) -> Void)?
@IBAction func confirmButtonTapped() {
completionHandler?("闭包返回的数据")
dismiss(animated: true)
}
}
// 在A页面
class AViewController: UIViewController {
func openBPage() {
let bVC = BViewController()
bVC.completionHandler = {

最低0.47元/天 解锁文章
866

被折叠的 条评论
为什么被折叠?



