swift 如何在forEach循环中缩放单个图像?

sqxo8psd  于 2023-02-18  发布在  Swift
关注(0)|答案(1)|浏览(131)

我有一个包含20个项目的ListView,并在ForEach循环中使用了以下Image:

Image(systemName: "heart").foregroundColor(.red).onTapGesture {
        selected.toggle()
        favLists.append(country.id)
        favLists = favLists.removingDuplicates()
    }
.scaleEffect(self.selected ? 1.5 : 1)

问题是selected是一个单变量,所以它会切换列表中所有项的状态。我如何声明依赖于索引项数量的动态状态?

cx6n0qe3

cx6n0qe31#

试试这个方法,...to scale individual image within a ForEach loop,对我很有效:

struct ContentView: View {
    @State var selected = "heart"
    
    var body: some View {
        VStack (spacing: 55) {
            ForEach(["globe", "house", "person", "heart"], id: \.self) { name in
                Image(systemName: name).id(name)
                    .onTapGesture { 
                       selected = name 
                       // ....other code
                    }
                    .foregroundColor(selected == name ? .red : .blue)
                    .scaleEffect(selected == name ? 2.5 : 1)
            }
        }
    }
}

相关问题