在我正在编写的 swiftUI 视图中,我需要使用 a ForEach
,访问列表的每个元素及其索引。我能找到的关于这个的大部分信息都说是用.enumerated()
在ForEach(Array(values.enumerated()), id: \.offset) { index, value in }
但是,当我尝试这样做时,我认为:
/// A popover displaing a list of items.
struct ListPopover: View {
// MARK: Properties
/// The array of vales to display.
var values: [String]
/// Whether there are more values than the limit and they are concatenated.
var valuesConcatenated: Bool = false
/// A closure that is called when the button next to a row is pressed.
var action: ((_ index: Int) -> Void)?
/// The SF symbol on the button in each row.
var actionSymbolName: String?
// MARK: Initializers
init(values: [String], limit: Int = 10) {
if values.count > limit {
self.values = values.suffix(limit - 1) + ["\(values.count - (limit - 1)) more..."]
valuesConcatenated = true
} else {
self.values = values
}
}
// MARK: Body
var body: some View {
VStack {
ForEach(Array(values.enumerated()), id: \.offset) { index, value in
HStack {
if !(index == values.indices.last && valuesConcatenated) {
Text("\(index).")
.foregroundColor(.secondary)
}
Text(value)
Spacer()
if action != nil && !(index == values.indices.last && valuesConcatenated) {
Spacer()
Button {
action!(index)
} label: {
Image(systemName: actionSymbolName ?? "questionmark")
}
.frame(alignment: .trailing)
}
}
.if((values.count - index) % 2 == 0) { view in
view.background(
Color(.systemGray5)
.cornerRadius(5)
)
}
}
}
}
}
我得到了The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
在线错误var body: some View {
我还注意到这段代码会导致一些其他问题,比如让 Xcode 自动完成非常慢。
有什么想法可以解决这个问题吗?这似乎是一个非常简单的观点,我认为我正在做ForEach
我应该做的。
谢谢!