簡體   English   中英

SwiftUI 列表與 NavigationLink 和按鈕

[英]SwiftUI List with NavigationLink and Buttons

我有一個計數器列表 - 列表中的每個元素都是一個帶有數字和加號/減號按鈕的計數器,用戶可以單擊以增加或減少計數器。 現在我添加了一個 NavigationLink 以便用戶可以 go 到每個計數器的詳細視圖。 現在的問題是,無論您單擊列表的何處,總是會推送詳細信息視圖-即使您單擊其中一個按鈕(計數器增加,然后通過 NavigationLink 推送詳細信息視圖)-我只想在用戶使用 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)")
    }
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM