SwiftUI 将列表中的行间距减少为空

mic*_*ica 4 swiftui swiftui-list

我想将列表中的行距减少为空。

\n\n

我尝试减少填充没有成功。\n设置 \xc2\xb4.environment(.defaultMinListRowHeight, 0)\xc2\xb4 有很大帮助。

\n\n
struct ContentView: View {\n  @State var data : [String] = ["first","second","3rd","4th","5th","6th"]\n\n  var body: some View {\n    VStack {\n      List {\n        ForEach(data, id: \\.self)\n        { item in\n          Text("\\(item)")\n          .padding(0)\n          //.frame(height: 60)\n          .background(Color.yellow)\n        }\n        //.frame(height: 60)\n        .padding(0)\n        .background(Color.blue)\n      }\n      .environment(\\.defaultMinListRowHeight, 0)\n      .onAppear { UITableView.appearance().separatorStyle = .none }\n      .onDisappear { UITableView.appearance().separatorStyle = .singleLine }\n    }\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

将 \xc2\xb4separatorStyle\xc2\xb4 更改为 \xc2\xb4.none\xc2\xb4 仅删除了该行,但留下了空格。
\n列表行或行之间的分隔符是否有额外的 \xc2\xb4hidden\xc2\xb4 视图?\n如何控制?

\n\n

会使用ScrollView而不是一个List好的解决方案吗?

\n\n
ScrollView(.horizontal, showsIndicators: true)\n        {\n      //List {\n        ForEach(data, id: \\.self)\n        { item in\n          HStack{\n          Text("\\(item)")\n            Spacer()\n          }\n
Run Code Online (Sandbox Code Playgroud)\n\n

它也适用于大型数据集吗?

\n

Asp*_*eri 7

嗯,实际上并不奇怪——.separatorStyle = .none工作正常。我想您混淆了文本背景和单元格背景 - 它们被不同的修饰符改变。请找到下面经过测试和工作的代码(Xcode 11.2 / iOS 13.2)

演示

struct ContentView: View {
  @State var data : [String] = ["first","second","3rd","4th","5th","6th"]

  var body: some View {
    VStack {
      List {
        ForEach(data, id: \.self)
        { item in
          Text("\(item)")
            .background(Color.yellow) // text background
            .listRowBackground(Color.blue) // cell background
        }
      }
      .onAppear { UITableView.appearance().separatorStyle = .none }
      .onDisappear { UITableView.appearance().separatorStyle = .singleLine }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

更新:

无法避免黄色文本之间的蓝色空间吗?

从技术上讲,是的,这是可能的,但是对于演示,它使用硬编码值,并且不难适应一些值,而动态计算它可能具有挑战性......无论如何,这里是

演示2

它需要压缩堆栈、抵抗内容填充和限制环境的组合:

  List {
    ForEach(data, id: \.self)
    { item in
        HStack {                                 // << A
          Text("\(item)")
            .padding(.vertical, 2)               // << B
        }
        .listRowBackground(Color.blue)
        .background(Color.yellow)
        .frame(height: 12)                       // << C
    }
  }
  .environment(\.defaultMinListRowHeight, 12)    // << D
Run Code Online (Sandbox Code Playgroud)