You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过多个Segue实现ViewController间的数据传递

如何通过多个Segue向其他ViewController传递数据?

这其实是iOS开发中很常见的场景,核心思路是利用UIKit提供的prepare(for:sender:)方法,结合Segue的唯一标识符来区分不同的跳转逻辑,从而给对应的目标ViewController传递数据。下面结合你的代码示例来一步步说明:

步骤1:给Segue设置唯一标识符

首先要确保你在Storyboard中给每个Segue都设置了独一无二的Identifier(比如你代码里的"profile"和"contact"),这样才能在代码中准确区分不同的跳转。

步骤2:在源ViewController中实现数据传递逻辑

在发起Segue的ViewController中,重写prepare(for:sender:)方法,通过switch语句判断Segue的标识符,然后将数据安全赋值给目标ViewController的对应属性:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    switch segue.identifier { 
    case "profile"? : 
        // 安全向下转型为目标ViewController类型,避免类型不匹配崩溃
        if let destinationVC = segue.destination as? Profile { 
            destinationVC.username = "demo" 
        } 
    case "contact"?: 
        if let destinationVC = segue.destination as? Contact { 
            destinationVC.email = "email1@xxxxx.com" 
        } 
    default: 
        print("没有匹配到对应的Segue") 
    } 
} 

代码里的?是可选绑定的简化写法,用于处理标识符可能为nil的情况,避免不必要的崩溃。

步骤3:在目标ViewController中定义接收数据的属性

在每个目标ViewController中,定义用于接收数据的属性(建议给默认值或者使用可选类型,避免未赋值导致的异常):

Profile ViewController示例

class Profile: UIViewController { 
    // 定义接收用户名的属性,给默认值避免空值问题
    var username = "" 

    override func viewDidLoad() { 
        super.viewDidLoad() 
        // 在这里可以使用接收到的数据,比如显示在界面控件上或者打印验证
        print("接收到的用户名:\(username)") 
    } 
} 

Contact ViewController示例

class Contact: UIViewController { 
    var email = "" 

    override func viewDidLoad() { 
        super.viewDidLoad() 
        print("接收到的邮箱:\(email)") 
    } 
} 

额外小提示

  • 如果你需要传递更复杂的数据(比如自定义模型对象),只需要把属性类型换成对应的模型类即可,逻辑完全一致。
  • 如果Segue是通过代码触发的(比如调用performSegue(withIdentifier:sender:)),可以把需要传递的额外数据放在sender参数中,在prepare方法里取出使用。

内容的提问来源于stack exchange,提问作者user9212972

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:17:25