首页 > 解决方案 > 三元运算符问题 SwiftUI

问题描述

我在我的 swiftui 视图中使用三元运算符来更改项目的前景色。当使用它作为代码时,一切正常编译:

Circle()
     .frame(width: 10, height: 10)
     .foregroundColor(item.amount < 10 ? Color.green : Color.red)

使用它时,我的项目无法构建,我的 Mac 的 CPU 开始飙升,风扇启动等。任何人知道出了什么问题吗?

Circle()
     .frame(width: 10, height: 10)
     .foregroundColor(item.amount < 10 ? Color.green : (item.amount < 100 ? Color.orange : Color.red))

完整代码:

struct ContentView: View {

    @ObservedObject var expenses = Expenses()
    @State private var showAddExpense = false

    var body: some View {
        NavigationView {
            List {
                ForEach (expenses.items) { item in
                    HStack {
                        VStack(alignment: .leading) {
                            Text(item.name)
                                .font(.headline)
                            Text(item.type)
                        }
                        Spacer()
                        Text("€\(item.amount)")
                        Circle()
                            .frame(width: 10, height: 10)
                            .foregroundColor(item.amount < 10 ? Color.green : (item.amount < 100 ? Color.orange : Color.red))
                    }
                }
                .onDelete(perform: removeItem)

            }
            .navigationBarTitle("iExpense")
            .navigationBarItems(leading: EditButton(), trailing:
                Button(action: {
                    self.showAddExpense = true
                }
                ) {
                    Image(systemName: "plus")
            })
        }
        .sheet(isPresented: $showAddExpense) {
            AddView(expenses: self.expenses)
        }

    }
    func removeItem(at index: IndexSet) {
        expenses.items.remove(atOffsets: index)
    }
}

工作表修改器上显示错误,但这个是正确的。

错误信息

标签: swiftxcodeswiftui

解决方案


打破较小组件的主体结构,如下所示

ForEach (expenses.items) { item in
    self.listRow(for: item)  // << extract !!
}
.onDelete(perform: removeItem)

,比如说,私有行生成器函数

private func listRow(for item: Item) -> some View { // << your item type here
    HStack {
        VStack(alignment: .leading) {
            Text(item.name)
                .font(.headline)
            Text(item.type)
        }
        Spacer()
        Text("€\(item.amount)")
        Circle()
            .frame(width: 10, height: 10)
            .foregroundColor(item.amount < 10 ? Color.green : (item.amount < 100 ? Color.orange : Color.red))
    }
}

推荐阅读