【问题标题】:Limit SwiftUI modifier .onMove() to current list only将 SwiftUI 修饰符 .onMove() 限制为仅当前列表
【发布时间】:2021-08-13 19:48:40
【问题描述】:

我在 List/ForEach 中声明了两个单独的项目列表,如下所示:

List {
    ForEach(model) { item in
        ItemView(item)
            .tag(item.id)
    }
    .onMove(perform: { rows, newIndex in
        model.move(items: rows, destination: newIndex)
    })
}

两个列表使用不同的模型,由其 ID 标识。不过,在 macOS 上,我意识到我可以将项目从一个列表拖到另一个列表,尽管它们的 ID 不同。

是否有可能在拖动时禁用另一个列表的拖放功能(例如通过.onInsert())?我已经使用NSItemProviderReadingNSItemProviderWriting 实现了一个功能,以便能够检测用户何时开始拖动。

【问题讨论】:

  • 我读了你的第一行,你在另一个列表中有 2 个列表。那是对的吗?还是 2 个单独的列表?
  • 有 2 个单独的列表
  • 我假设您使用的是 macos,因为在 ios-15 和 macCatalyst 上它运行良好。
  • 正确!忘记说了

标签: swift macos swiftui


【解决方案1】:

您可以尝试忽略插入,例如对我有用的测试代码:

struct ContentView: View {
    @State private var model1 = ["One", "Two", "Three", "Four"]
    @State private var model2 = ["Five", "Six", "Seven", "Eight"]
    
    var body: some View {
        VStack {
            List {
                ForEach(model1, id: \.self) { item in
                    Text(item)
                }
                .onMove { (indexSet, index) in
                    model1.move(fromOffsets: indexSet, toOffset: index)
                }
                .onInsert(of: [UTType.text]) { pos,prov in
                    print("\n-----> ignoring insert in model1")
                }
            }
            Divider()
            List {
                ForEach(model2, id: \.self) { item in
                    Text(item)
                }
                .onMove { (indexSet, index) in
                    model2.move(fromOffsets: indexSet, toOffset: index)
                }
                .onInsert(of: [UTType.text]) { pos,prov in
                    print("\n-----> ignoring insert in model2")
                }
            }
        }
    }
}

【讨论】:

  • 感谢您的示例代码。这确实是我目前的解决方法。尽管如此,当从一个列表拖动到另一个列表时,“插入”指示器仍然存在,这可能会使用户感到困惑,而且根本不是一个干净的解决方案。
猜你喜欢
  • 1970-01-01
  • 2019-12-29
  • 2020-01-30
  • 2023-04-06
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 2021-06-12
  • 2020-11-06
相关资源
最近更新 更多