swift - 三元运算符问题 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)
}
}
工作表修改器上显示错误,但这个是正确的。
解决方案
打破较小组件的主体结构,如下所示
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))
}
}
推荐阅读
- sql-server - 连接到单用户模式 SQL Server 但获取错误帐户已禁用 -
- java - spring retry 中如何为不同的异常配置不同的延迟值?
- java - JAXBSource 的构造函数中的 contentObject 是什么
- python - 在进程结束前两次使用命令时出错 [Discord.py Rewrite]
- vba - 运行时出现问题,使用 if 语句进行下一个循环
- reactjs - 如何显示菜单项取决于使用 reactjs 的条件
- c - 错误:此处不允许函数定义。如何纠正这个?
- java - Eclipselink - 分离实体内存泄漏
- excel - 在 Excel 中计算某个位置的重叠车辆
- c - memfd_create 和 fexecve 如何协同工作