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

如何在SwiftUI的Zip函数中修改数组索引以展示对应图片

解决思路及代码修改

问题核心是没有把选中行对应的图片数据传递到详情页,当前QuestionView每次都会新建ViewModel并固定取第0组数据,所以所有行点击后都显示同一组图片。以下是具体修改步骤:

1. 调整QuestionView,接收选中的ImageInTheScreen数据

不需要在QuestionView里重新初始化ViewModel,直接传入用户点击的那一行对应的ImageInTheScreen实例,就能拿到对应组的图片和颜色数据。

2. 在QuestionView中处理当前数据的Zip组合

直接对传入的ImageInTheScreen对象的imagesString和colorString做zip操作,不需要依赖ViewModel的计算属性。

修改后的完整代码

import SwiftUI

struct ImageInTheScreen: Identifiable {
    var id = UUID()
    let imagesString: [String]
    let colorString: [Color]
    let rowString: String
}

class ViewModel {
    var images: [ImageInTheScreen] = [
        ImageInTheScreen(imagesString: ["super", "baloon"], colorString: [.red, .blue], rowString: "Super Baloon"),
        ImageInTheScreen(imagesString: ["sky", "good"], colorString: [.red, .blue], rowString: "Sky good")
    ]
}

struct ContentView: View {
    let vm: ViewModel
    var body: some View {
        NavigationView {
            List {
                ForEach(vm.images) { sentence in
                    NavigationLink(
                        // 把选中的sentence传递给QuestionView
                        destination: QuestionView(selectedItem: sentence),
                        label: {
                            Text(sentence.rowString)
                        }
                    )
                }
            }
        }
    }
}

struct QuestionView: View {
    // 接收从列表页传过来的选中数据
    let selectedItem: ImageInTheScreen
    
    var body: some View {
        HStack {
            // 对当前选中数据的数组做zip组合
            ForEach(Array(zip(selectedItem.imagesString, selectedItem.colorString)), id: \.0) { imageName, _ in
                Image(imageName)
                    .resizable()
                    .frame(width: 140, height: 140)
                    .scaledToFit()
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(vm: ViewModel())
    }
}

关键修改点说明

  • 移除了ViewModel中的arrayForLoop计算属性,无需固定取第0组数据,改为根据选中行动态处理
  • NavigationLink的destination改为传入选中的sentence实例,把对应行的数据传递到详情页
  • QuestionView新增selectedItem属性接收数据,直接在视图中通过Array(zip(...))组合当前选中项的图片和颜色数组(ForEach需要可遍历集合,zip返回的Zip2Sequence转成Array即可)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 02:05:16