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

UIStoryBoard Segue无法传值:向Second ViewController传Bool值始终为false

解决Segue传递Bool值始终为false的问题

我来帮你排查这个问题!你遇到的情况很常见,大概率是在segue传值的关键环节出了疏漏,咱们一步步来解决:

第一步:检查SecondViewController的变量声明

首先要确保你在目标页面的Bool变量是可修改的实例变量,不能用let声明常量,同时要避免在生命周期方法里意外重置它:

class SecondViewController: UIViewController {
    // 用var声明,默认值设为false,等待传值覆盖
    var targetBoolValue: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()
        // 这里不要重新给targetBoolValue赋值为false!
        print("接收到的Bool值:\(targetBoolValue)") // 可以添加打印测试
    }
}

第二步:完善FirstViewController的prepare方法

你提供的代码里prepare(for segue:方法没写完,这正是传值的核心环节。必须在这里正确匹配segue、强转目标控制器并完成赋值:

import UIKit 
class ViewController: UIViewController { 
    override func viewDidLoad() { 
        super.viewDidLoad() 
    } 

    @IBAction func moveTo(_ sender: Any) { 
        self.performSegue(withIdentifier: "Move2", sender: self) 
    } 

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        super.prepare(for: segue, sender: sender)
        
        // 1. 先验证segue的标识符是否完全匹配(大小写敏感!)
        guard segue.identifier == "Move2" else {
            return
        }
        
        // 2. 安全强转目标控制器为SecondViewController类型
        guard let secondVC = segue.destination as? SecondViewController else {
            print("无法将目标控制器强转为SecondViewController")
            return
        }
        
        // 3. 给目标控制器的Bool变量赋值(替换成你需要传递的具体值,比如true)
        secondVC.targetBoolValue = true
    }
}

第三步:排查常见的易错点

  • 确认Storyboard里的segue标识符完全一致:检查拼写、大小写,确保是"Move2"
  • 不要在SecondVC的init或awakeFromNib里访问这个变量:此时传值还未完成,只能在viewDidLoad及之后的方法里使用
  • 检查SecondVC的其他方法:比如viewWillAppear里是否意外将这个变量重置为false了

内容的提问来源于stack exchange,提问作者Vimalkumar N.M.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:42:28