iOS第十三篇 iOS页面间通信方案全面解析

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 = {
   
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HiHi_Peter

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值