【问题标题】:SwiftUI List with NavigationLink and Buttons带有 NavigationLink 和按钮的 SwiftUI 列表
【发布时间】:2020-07-25 04:44:22
【问题描述】:

我有一个计数器列表 - 列表中的每个元素都是一个带有数字的计数器,用户可以单击加/减按钮来增加或减少计数器。现在我添加了一个 NavigationLink,以便用户可以转到每个计数器的详细视图。现在的问题是,无论您单击列表的何处,总是会推送详细信息视图-即使您单击其中一个按钮(计数器增加,然后通过 NavigationLink 推送详细信息视图)-我只想在用户使用 NavigationLink点击数字或其他地方,但如果用户点击按钮,当然不会。如何做到这一点?

NavigationView {
        List {
            ForEach(counters, id: \.self) { counter in
                NavigationLink(destination: SingleCounterView(currentCounter: counter)) {
                    CounterCell(counter: counter)
                }
            }
        }
        .buttonStyle(PlainButtonStyle())
        .listStyle(GroupedListStyle())
}

【问题讨论】:

    标签: ios swift iphone xcode swiftui


    【解决方案1】:

    我进行了这个测试,以在 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)")
        }
    }
    }
    

    【讨论】:

    • 感谢您的回答。我添加了一个自定义 ButtonStyle 并且 ScaleEffect 以某种方式改变了这种行为。 struct PlusButton: ButtonStyle { func makeBody(configuration: Self.Configuration) -> some View { configuration.label .scaleEffect(configuration.isPressed ? 0.8 : 1.0) } }
    • 我已将您的按钮样式添加到加号按钮,它仍然适用于我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    相关资源
    最近更新 更多