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

SwiftUI中向数组追加元素时如何传递不同颜色?

解决方案

要实现点击不同颜色按钮后,在SecondView中对应显示同颜色的人名,核心是给每个记录的名字关联对应的颜色信息,具体步骤如下:

1. 创建带颜色信息的数据模型

首先定义一个结构体,同时保存人名和对应的颜色,让它遵循Identifiable协议方便后续遍历:

struct NamedColor: Identifiable {
    let id = UUID()
    let name: String
    let color: Color
}

2. 修改ContentView的逻辑

把原来的appearedNames数组类型从[String]改成[NamedColor],点击按钮时,将当前人名和按钮对应的颜色一起存入数组:

struct ContentView: View {
    @State private var countdown = Timer.publish(every: 1, tolerance: 0.5, on: .main, in: .common).autoconnect().eraseToAnyPublisher()
    @State private var timeRemaining = 10
    @State private var isActive = false
    
    @State private var names = ["Steve", "Bill", "Jeff", "Elon", "Michael", "John", "Steven", "Paul"]
    // 修改数组类型为带颜色的模型数组
    @State private var appearedNames = [NamedColor]()
    @State private var currentPerson = ""
    
    var body: some View {
        NavigationView {
            ZStack {
                // 更新SecondView的参数类型
                NavigationLink(destination: SecondView(appearedNames: $appearedNames, countdown: countdown), isActive: $isActive) {
                    EmptyView()
                }
                VStack {
                    Text("\(timeRemaining)")
                        .font(.largeTitle)
                        .padding()
                        .onReceive(countdown) { _ in
                            if timeRemaining > 0 {
                                timeRemaining -= 1
                            }
                            if timeRemaining == 0 {
                                isActive = true
                            }
                        }
                    
                    HStack {
                        Button {
                            // 存入名字+红色标识
                            appearedNames.append(NamedColor(name: currentPerson, color: .red))
                            changePerson()
                        } label: {
                            Text(currentPerson)
                                .foregroundColor(.red)
                                .font(.largeTitle)
                        }
                        
                        Button {
                            // 存入名字+绿色标识
                            appearedNames.append(NamedColor(name: currentPerson, color: .green))
                            changePerson()
                        } label: {
                            Text(currentPerson)
                                .foregroundColor(.green)
                                .font(.largeTitle)
                        }
                    }
                }
                .onAppear {
                    changePerson()
                }
            }
        }
    }
    
    func changePerson() {
        if names.count > 0 {
            let index = Int.random(in: 0..<names.count)
            currentPerson = names[index]
            names.remove(at: index)
        }
    }
}

3. 更新SecondView显示对应颜色

修改SecondView的绑定变量类型,遍历数组时给文本设置对应的颜色:

import SwiftUI
import Combine

struct SecondView: View {
    // 修改绑定类型为[NamedColor]
    @Binding var appearedNames: [NamedColor]
    var countdown: AnyPublisher<Date,Never>
    @State private var counter = 0
    
    var body: some View {
        VStack {
            ScrollViewReader { proxy in
                ScrollView(showsIndicators: false) {
                    // 遍历带颜色的模型数组
                    ForEach(0...counter, id: \.self) { index in
                        Text(appearedNames[index].name)
                            .font(.system(size: 70))
                            // 设置对应颜色
                            .foregroundColor(appearedNames[index].color)
                            .id(index)
                            .onAppear {
                                proxy.scrollTo(index)
                            }
                    }
                }
            }
        }
        .navigationBarBackButtonHidden(true)
        .onReceive(countdown) { _ in
            if counter < appearedNames.count - 1 {
                counter += 1
            }
        }
    }
}

这样修改后,点击红色按钮时,人名会关联红色存入数组,在SecondView里就会显示红色文本;点击绿色按钮则对应显示绿色文本,完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 17:27:13