【发布时间】:2020-03-23 02:45:18
【问题描述】:
我正在尝试在结构中使用带有布尔值的 if 语句,然后查看是否应该使用该数据显示内容视图。我不断收到错误“对成员'索引'的模糊引用”,但我知道这不是实际问题,它只是 swiftUI 说当它是 forEach 内部的东西时,forEach 上有一个错误。这是结构体定义,其中 needsToBeDeleted 默认为 false,因为它应该在首次创建时显示
import Foundation
struct SEvent {
var eventName:String;
var timeSpent:String;
var timeStarted:Date;
var lastStarted:Date?;
var needsToBeDeleted = false;
}
这就是我在事件数组中迭代的部分
ForEach(arrayOfEvents.indices, id: \.self) { index in
if !self.arrayOfEvents[index].needsToBeDeleted {
EventContentView(eventName: self.arrayOfEvents[index].eventName, timeSpent:
self.arrayOfEvents[index].timeSpent, shouldDelete:
self.$arrayOfEvents[index].needsToBeDeleted)
}
}
如果有帮助,这也是数组声明
@State private var arrayOfEvents = [SEvent]();
编辑:
这是事件内容查看代码
import SwiftUI
struct EventContentView: View {
var eventName:String;
var timeSpent:String;
var startStop = ["Start", "Stop"];
@State var deleteTrigger = false;
var buttonColor = [Color.blue, Color.yellow]
@State var i = 0;
@Binding var shouldDelete:Bool;
var body: some View {
VStack{
VStack{
Text("\(eventName)")
.frame(minWidth: 0, idealWidth: 150, maxWidth: 200, minHeight: 0, idealHeight: 50, maxHeight: 75, alignment: .center)
Text("\(timeSpent)")
.frame(minWidth: 0, idealWidth: 150, maxWidth: 200, minHeight: 0, idealHeight: 50, maxHeight: 100, alignment: .leading)
if !deleteTrigger {
HStack {
Button(action: {
if self.i == 0{
self.i = 1
}
else if self.i == 1 {
self.i = 0
}
}) {
Text(startStop[i])
}
.foregroundColor(buttonColor[i])
.frame(minWidth: 0, idealWidth: 50, maxWidth: 100, minHeight: 0, idealHeight: 20, maxHeight: 40, alignment: .leading)
Button(action: {
self.deleteTrigger = true;
}) {
Text("Delete")
}
.foregroundColor(.red)
.animation(.interactiveSpring(response: 1, dampingFraction: 0.5, blendDuration: 1.5))
.frame(minWidth: 0, idealWidth: 50, maxWidth: 100, minHeight: 0, idealHeight: 20, maxHeight: 40, alignment: .trailing)
}
}
else{
HStack {
Button(action: {
self.shouldDelete = true
}) {
Text("Delete")
}
.foregroundColor(.red)
.frame(minWidth: 0, idealWidth: 50, maxWidth: 100, minHeight: 0, idealHeight: 20, maxHeight: 40, alignment: .leading)
Button(action: {
self.deleteTrigger = false;
}) {
Text("Don't Delete")
}
.foregroundColor(.green)
.animation(.easeInOut)
.frame(minWidth: 0, idealWidth: 50, maxWidth: 100, minHeight: 0, idealHeight: 20, maxHeight: 40, alignment: .trailing)
}
}
}
.frame(minWidth: 0, maxWidth: 200, minHeight: 20, idealHeight: 30, maxHeight: 150, alignment: .center)
}
.padding()
.overlay(
RoundedRectangle(cornerRadius: 5.0)
.stroke(Color.black, lineWidth: 1)
.shadow(radius: 5)
)
.padding()
}
}
删除视图的具体部分是这个按钮,它将绑定变量 shouldDelete 更改为 true,从而将 arrayOfEvents 中 SEvent 结构的 needsToBeDeleted 元素更改为 true
Button(action: {
self.shouldDelete = true
})
{
Text("Delete")
}
【问题讨论】:
-
这与
if无关,这种if在视图生成器中是允许的。你会显示更多代码吗?还有EventContentView。
标签: xcode if-statement struct foreach swiftui