![](/img/trans.png)
[英]NavigationLink when destination's required parameter is from optional state variable
[英]Optional @State variable not initializing
我希望能够打开一个工作表视图,用户在其中点击列表上的某些内容,并且来自该点击的列表单元格的所有信息都显示在工作表视图上。 但是,我很难尝试将可选的 @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?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.