我有一个计数器列表 - 列表中的每个元素都是一个带有数字的计数器,用户可以单击加/减按钮来增加或减少计数器。现在我添加了一个 NavigationLink 以便用户可以转到每个计数器的详细 View 。现在的问题是,无论您单击列表的何处,总是会推送详细信息 View -即使您单击其中一个按钮(计数器增加,然后通过 NavigationLink 推送详细信息 View )-我只想在用户使用 NavigationLink点击数字或其他地方,但如果用户点击按钮,当然不会。如何才能做到这一点?
NavigationView {
List {
ForEach(counters, id: \.self) { counter in
NavigationLink(destination: SingleCounterView(currentCounter: counter)) {
CounterCell(counter: counter)
}
}
}
.buttonStyle(PlainButtonStyle())
.listStyle(GroupedListStyle())
}
最佳答案
我进行了这个测试,以在 NavigationView 中显示带有加号和减号按钮的 CounterCell。如果您点击按钮,计数器会增加,如果您点击人字形或按钮外部,则会出现目的地。
@State var counters = ["a","b","c"]
var body: some View {
NavigationView {
List {
ForEach(counters, id: \.self) { counter in
NavigationLink(destination: Text(counter)) {
CounterCell(counter: counter)
}
}
}
.buttonStyle(PlainButtonStyle())
.listStyle(GroupedListStyle())
}.navigationViewStyle(StackNavigationViewStyle())
}
struct CounterCell: View {
@State var counter: String
@State var inc = 0
var body: some View {
HStack {
Button(action: { self.inc += 1 }) {
Text("plus")
}
Button(action: { self.inc -= 1 }) {
Text("minus")
}
Text(" counter: \(counter) value: \(inc)")
}
}
}
关于ios - 带有 NavigationLink 和按钮的 SwiftUI 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61174089/