如何防止出现确认对话框时更新可选列表?

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

让我们选择一个

List
,如下:

import SwiftUI

struct ContentView: View {
    @State private var elements: Set<UUID> = [.init(), .init(), .init()]
    @State private var selection: Set<UUID> = []
    @State private var isConfirmationDialogPresented: Bool = false
    
    var body: some View {
        NavigationStack {
            List(
                elements.sorted(),
                id: \.self,
                selection: $selection,
                rowContent: { Text(String(describing: $0)).lineLimit(1) }
            )
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    EditButton()
                }
                ToolbarItem(placement: .bottomBar) {
                    Button(
                        "Delete \(selection.count) element(s)",
                        role: .destructive,
                        action: { isConfirmationDialogPresented = true }
                    )
                    .disabled(selection.isEmpty)
                    .confirmationDialog(
                        "Delete \(selection.count) elements(s)",
                        isPresented: $isConfirmationDialogPresented,
                        actions: {
                            Button("Delete \(selection.count) element(s)", action: {
                                elements = elements.subtracting(selection)
                            })
                        }
                    )
                }
            }
        }
    }
}

当点击

Button
显示确认对话框时,可选择的
List
将被重置(所有选定的行将变为未选定状态,即
selection
值变为空
Set
)。如何预防这种情况?

注意:将

.confirmationDialog
移动到
List
会导致相同的行为。

使用 Xcode 16 beta 4 • iOS 18 进行测试。

ios swift swiftui
1个回答
0
投票

我发现这只发生在编辑模式下。如果您选择某些列表行然后按删除按钮,而不按“编辑”,则所选行将被成功删除。我不确定这是否是故意的。

我发现有效的方法是将选定的行传递给

presenting:
参数。显然,在评估时,
selection
尚未被清除。然后你可以使用闭包参数访问它。

.confirmationDialog(
    "Delete \(selection.count) elements(s)",
    isPresented: $isConfirmationDialogPresented,
    presenting: selection, // <------ here!
    actions: { idsToDelete in
        Button("Delete \(idsToDelete.count) element(s)", action: {
            elements.subtract(idsToDelete)
        })
    }
)
© www.soinside.com 2019 - 2024. All rights reserved.