【问题标题】:Strange buttons behaviour in a list (SwiftUI)列表中的奇怪按钮行为 (SwiftUI)
【发布时间】:2020-11-15 03:51:15
【问题描述】:

在以下 SwiftUI 代码中,我注意到了一些意外行为。

我想知道这是否是一个错误,这是正常的还是我只是遗漏了一些明显的东西。

List {
    ForEach(self.myList, id: \.self.name) {
        item in
        HStack {
            Spacer()
            Button(action: {
                print("Button One tapped!")
                ....
            }) {
                item.name.map(Text.init)
                    .font(.largeTitle)
                    .foregroundColor(.secondary)
            }
            Spacer()
            Button(action: {
                print("Button Two tapped!")
                ....
            }) {
                Image(systemName: "pencil.circle")
                    .font(.title)
                    .foregroundColor(.secondary)
                    .padding(.leading, 17)
            }
        }
    }
    .onDelete(perform: deleteFunc)
}

现在,当连续点击两个按钮中的一个时会发生这种情况。 我可以看到这两条消息:

Button One tapped!
Button Two tapped!

我希望只看到一条消息,具体取决于点击的按钮。

如果消息的顺序根据点击的按钮而变化;我可以使用一两个布尔值来强制执行我想要的最终结果。但是这两条消息总是以相同的顺序出现。

有没有人有同样的经历?或者有人看出有什么错误吗?

【问题讨论】:

    标签: ios swift button swiftui swiftui-list


    【解决方案1】:

    使用 PlainButtonStyle(或任何自定义),因为 List 会自动检测默认按钮样式以突出显示整行。

    这是一个简化的(来自您的代码)演示:

    struct DemoListWithButtons: View {
        var body: some View {
            List {
                ForEach(0..<5, id: \.self) {
                    item in
                    HStack {
                        Spacer()
                        Button(action: {
                            print("Button One tapped!")
                        }) {
                            Text("First")
                        }.buttonStyle(PlainButtonStyle()) // << here !!
                        Spacer()
                        Button(action: {
                            print("Button Two tapped!")
                        }) {
                            Text("Second")
                        }.buttonStyle(PlainButtonStyle()) // << here !!
                    }
                }
            }
        }
    }
    

    【讨论】:

    • 是的。做你所写的,甚至只对一个按钮就可以了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    相关资源
    最近更新 更多