列表中的第一项总是被选中 [英] First item in a List is always selected
问题描述
我有一个项目列表,我想让导航到详细信息视图成为可能.但是,列表中的第一个元素总是传递给这个视图,这可能是什么问题?
I have a list of items, I want to make it possible to navigate to the details view. However, the first element in the list is always passed to this view, what could be the problem?
struct ContentView: View {
var array: [Object] = [Object(id: .init(),property: 1),Object(id: .init(),property: 2),Object(id: .init(),property: 3)]
@State var showAlert = false
@State var showDetailsView = false
var body: some View {
NavigationView{
List{
ForEach(array){ item in
VStack{
Text(String(item.property))
}.onTapGesture(){ self.showAlert.toggle()}
.alert(isPresented: $showAlert){
Alert(title: Text("show details view?"), message: Text(""),
primaryButton: .default (Text("Show")) {
showDetailsView.toggle()
},
secondaryButton: .cancel()
)
}
.fullScreenCover(isPresented: $showDetailsView){ DetailsView(property: item.property) }
}
}
}
}
}
struct Object: Identifiable {
let id: UUID
var property: Int
}
struct DetailsView: View {
var property: Int?
var body: some View {
Text(String(property!))
}
}
无论我选择列表中的哪个项目,我都会得到这个结果:
I will get this result regardless of which item in the list I select:
推荐答案
在这种情况下,我们可以将像指挥棒这样的点击项从 ForEach
传递到 Alert
到 FullScreen
到 Details
.而且,当然,我们应该将相应的修饰符移出循环,它们不需要应用于每一行.
In this scenario we can pass clicked item like baton from ForEach
to Alert
to FullScreen
to Details
. And, of course, we should move corresponding modifiers out of cycle, they don't need to be applied to each row.
这是修改后的代码.使用 Xcode 12.1/iOS 14.1 测试.
Here is a modified code. Tested with Xcode 12.1 / iOS 14.1.
struct ContentView: View {
var array: [Object] = [Object(id: .init(),property: 1),Object(id: .init(),property: 2),Object(id: .init(),property: 3)]
@State var alertItem: Object?
@State var selectedItem: Object?
var body: some View {
NavigationView{
List{
ForEach(array){ item in
VStack{
Text(String(item.property))
}.onTapGesture(){ self.alertItem = item}
}
}
.alert(item: $alertItem) { item in
Alert(title: Text("show details view?"), message: Text(""),
primaryButton: .default (Text("Show")) {
selectedItem = item
},
secondaryButton: .cancel()
)
}
.fullScreenCover(item: $selectedItem){ DetailsView(property: $0.property) }
}
}
}
这篇关于列表中的第一项总是被选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!