swiftui - SwiftUI List 选择:最初必须点击两次才能取消选择项目

为什么必须点击两次才能取消选择“项目 1”?难道我做错了什么?如果没有,是否有解决方法?它发生在模拟器和我的 iPhone 上。

脚步:

  1. 点击“项目 1”。什么都没发生。不要先点击其他项目。此外,它只发生一次,因此重新启动应用程序以重试。
  2. 再次点击“项目 1”。它被取消选择。
import SwiftUI

struct ContentView: View {
    @State private var selectedItems: Set<Int> = [1]
    
    var body: some View {
        NavigationView { // Some apparent solutions do not work inside a NavigationView
            List(selection: $selectedItems) {
                Text("Item 1").tag(1)
                Text("Item 2").tag(2)
                Text("Item 3").tag(3)
            }.environment(\.editMode, Binding.constant(EditMode.active))
        }
    }
}

回答1

不知道为什么,但它似乎是对 .environment 的访问。

使用经典的@Environment var 对我有用:

struct ContentView: View {
    
    @State private var selectedItems: Set<Int> = [1]
    @Environment(\.editMode) var editMode
    
    var body: some View {
        
        List(selection: $selectedItems) {
            Text("Item 1").tag(1)
            Text("Item 2").tag(2)
            Text("Item 3").tag(3)
        }
//        .environment(\.editMode, Binding.constant(EditMode.active))
        
        // try this instead
        .onAppear {
            editMode?.wrappedValue = EditMode.active
        }
    }
}

回答2

为防止双击问题,请在列表内的 onAppear 中设置选择:

import SwiftUI

struct ContentView: View {
    @State private var selectedItems: Set<Int> = []
    
    var body: some View {
        NavigationView { // Some apparent solutions do not work inside a NavigationView
            List(selection: $selectedItems) {
                Text("Item 1").tag(1)
                Text("Item 2").tag(2)
                Text("Item 3").tag(3).onAppear() { // onAppear inside the List!
                    selectedItems = [1]
                }
            }.environment(\.editMode, Binding.constant(EditMode.active))
        }
    }
}

请注意,此示例代码在每个 onAppear 上设置相同的选择。根据您的应用程序的行为方式,您将不得不对其进行更改。

相似文章

随机推荐

最新文章