为什么点击一个按钮时会触发两个按钮的操作?

问题描述 投票:0回答:1

我正在使用以下代码来制作升序和降序按钮。

@State private var sortDirection: SortDirection = .none

List {
    HStack {
        Button("Sort ASC") {
            sortDirection = .asc
            print("ss")
        }
        Spacer()
        Button("Sort DESC") {
            sortDirection = .desc
            print("dd")
        }
    }
    
    ForEach(sortedCustomers) { customer in
        Text(customer.name)
    }
}

当我点击任何按钮时,两个按钮操作都会被触发。发生了什么事,我怎样才能只触发被点击的按钮的操作?

swiftui
1个回答
-1
投票

将此作为答案,以便我可以显示我的代码,但我无法重现您的问题。这个最小的例子似乎表现得像你所期望的那样。每个按钮都有自己的作用。

import SwiftUI
@main
struct HelloWorldApp: App {
    
    var body: some Scene {
        WindowGroup {
            HelloWorldView()
        }
    }
}

struct HelloWorldView: View {
    @State private var sortDirection: SortDirection = .none
    enum SortDirection {
        case none, asc, desc
    }
    var sortedCustomers: [String] = ["Alice", "Bob", "Charlie"]
    var body: some View {
        VStack {
            List {
                HStack {
                    Button("Sort ASC") {
                        sortDirection = .asc
                        print("Ascending")
                    }
                    Spacer()
                    Button("Sort DESC") {
                        sortDirection = .desc
                        print("Descending")
                    }
                }
                
                ForEach(sortedCustomers, id: \.self) { customer in
                    Text(customer)
                }
            }
        }
        .navigationTitle("Button Question")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.