我希望能够打开一个工作表视图,用户在其中点击列表上的某些内容,并且该点击的列表单元格中的所有信息都显示在工作表视图上。但是,我很难尝试将可选的 @State 变量初始化为列表值。这是我得到的错误:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
State 变量似乎保持为空,因此代码会返回 nil 值。我怎样才能得到一个实际值,使它不为零?
如有任何帮助,我们将不胜感激。
我的代码如下:
struct ContentView: View {
@Environment(\.managedObjectContext) var managedObjContext
@FetchRequest(sortDescriptors: [SortDescriptor(\.date, order: .reverse)]) var counters: FetchedResults<Counter>
@State private var creatingCounter = false
@State private var editingCounter = false
@State private var selectedCounter: FetchedResults<Counter>.Element? // The optional State var.
var body: some View {
NavigationView {
VStack {
List {
ForEach(counters) { counter in
TimelineView(.periodic(from: .now, by: 1.0)) { timeline in
CounterCellView(title: counter.title ?? "", icon: counter.icon ?? "", color: counter.color ?? "", date: counter.date ?? Date())
}
.listRowSeparator(.hidden)
.onTapGesture {
selectedCounter = counter // I want the state var to be initialized to the tapped item on the list.
editingCounter.toggle()
}
}
.onDelete(perform: deleteCounter)
}
.listStyle(.inset)
}
.navigationTitle("Counters")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button {
creatingCounter.toggle()
} label: {
Image(systemName: "plus")
}
}
}
}
.sheet(isPresented: $creatingCounter) {
CreateCounterView(creatingCounter: $creatingCounter)
}
.sheet(isPresented: $editingCounter) {
EditCounterView(editingCounter: $editingCounter, counter: selectedCounter!) // Where I am getting the error.
}
}
func deleteCounter(at offsets: IndexSet) {
withAnimation {
offsets.map { counters[$0] }.forEach(managedObjContext.delete)
DataController().save(context: managedObjContext)
}
}
}
尝试这个方法:
删除所有
editingCounter
并使用类似这样的.sheet(item: $selectedCounter)
,而不是
你的.sheet(isPresented: $editingCounter)
:
.sheet(item: $selectedCounter) { kounter in // <-- here
if let theCounter = kounter {
//-- here, adjust the EditCounterView (ie remove the editingCounter)
EditCounterView(counter: theCounter)
}
}
如果需要,您可能需要声明
@State private var selectedCounter: Counter?
实际上可选状态变量必须以与普通变量不同的方式初始化。这是初始化状态变量的方法
例如 @State 变量计数? 这应该以这种方式初始化: _count=State(wrappedValue:你的值) 因此,您的状态变量将被更新,而不是 nil 。 所以在你的情况下你的代码应该修改为
.onTapGesture {
_selectedCounter = State(wrappedValue:counter)
editingCounter.toggle()
}