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

Swift开发如何实现VC1按钮点击跳转VC2并传递对应颜色作为标题

iOS Swift多按钮跳转传值解决方案

你当前代码的核心问题是prepare(for:sender:)方法里硬编码了固定的传值内容,且触发跳转时没有传递对应按钮的颜色标识,导致不管点击哪个按钮,VC2拿到的标题都是固定值。


优化方案1:通过sender参数传递颜色名称

修改各按钮的点击方法,把对应颜色名称作为sender参数传递,跳转时直接把该值传给VC2:

@IBAction func myBlackButton(_ sender: Any) {
    performSegue(withIdentifier: "VCColor", sender: "Black")
}

@IBAction func myPinkButton(_ sender: Any) {
    performSegue(withIdentifier: "VCColor", sender: "Pink")
}

@IBAction func myOrangeButton(_ sender: Any) {
    performSegue(withIdentifier: "VCColor", sender: "Orange")
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // 连续判空减少嵌套层级
    if segue.identifier == "VCColor",
       let destino = segue.destination as? ViewControllerColors,
       let colorTitle = sender as? String {
        destino.titulo = colorTitle
    }
}

优化方案2:合并按钮点击方法(适合按钮数量多的场景)

  1. 在Storyboard/Xib中给三个按钮分别设置tag值:黑色按钮tag设为0、粉色设为1、橙色设为2
  2. 把三个按钮的点击事件绑定到同一个IBAction上,通过tag判断点击的按钮:
@IBAction func colorButtonTapped(_ sender: UIButton) {
    let colorTitles = ["Black", "Pink", "Orange"]
    let selectedTitle = colorTitles[sender.tag]
    performSegue(withIdentifier: "VCColor", sender: selectedTitle)
}

prepare方法和方案1完全一致即可。


最后记得在VC2的viewDidLoad方法中把接收到的titulo赋值给导航栏标题:

override func viewDidLoad() {
    super.viewDidLoad()
    title = titulo
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:15:03