移除 Swift UI Xcode 11 中的空行

7
如何使用Swift UI在List中删除空行。以下是我的代码。
struct LandMarkList: View {
    var body: some View {
        NavigationView {
            List(LandMarkListData) { landmark in
                LandMarkRow(landmark: landmark)
            }

        .navigationBarTitle("List")
        }
    }
}

1
LandMarkListDataLandMarkRow中包含什么? - Michcio
5个回答

23
struct LandMarkList: View {
    var body: some View {
        NavigationView {
            List(LandMarkListData) { landmark in
                LandMarkRow(landmark: landmark)
            }

            .navigationBarTitle("List")
            .listStyle(GroupedListStyle())
        }
    }
}

最后,我通过添加 listStyle 找到了解决方案。


2
NavigationView {
   ...
   .listStyle(.grouped)
}

在您的情况下:
struct LandMarkList: View {
    var body: some View {
        NavigationView {
            List(LandMarkListData) { landmark in
                LandMarkRow(landmark: landmark)
            }

        .navigationBarTitle("List")
        .listStyle(.grouped)
        }
    }
}

在添加'.listStyle(.grouped)'后,出现了“无法推断通用参数'SelectionValue'”的错误。 - Shahbaz Akram

1
这得益于内省
我的代码。
List() {
  ...
}
.introspectTableView { tableView in
     tableView.separatorColor = UIColor.lightGray.withAlphaComponent(0.4)
     tableView.tableFooterView = UIView()   
}

1
这篇文章帮助我在 MacOS Catalina 10.15.5 Beta 下使用 Xcode 11.4 去除了 List 中的空行:
List(flights) { flight in
  FlightInfoRow(flightInfo: flight)
}.onAppear{UITableView.appearance().separatorColor = .clear}

如果您想在现有行中显示分隔线,您可以在自定义列表行视图中进行操作。
1. 在您的视图中使用单元格宽度和高度的信息与GeometryReader
VStack { 
  GeometryReader { geometry in
    HStack { Text("\(flight.airline)") }
  }
}

使用Path{ path in}绘制一条水平线,放置在内容信息下方,如下所示:
Path{ path in
  path.move(to: CGPoint(x: 0, y: geometry.size.height))
  path.addLine(to: CGPoint(x: geometry.size.width, y: geometry.size.height))
}.stroke(Color(.lightGray), lineWidth: 0.5)

这将创建类似于以下内容的东西(没有空行和分隔线的列表):

List without empty rows & separator lines


1

据我所知,目前在SwiftUI中没有办法从List中删除空单元格。但是,您仍然可以通过不使用List并手动创建Divider来摆脱空单元格(特别是所有不美观的分隔符)。尝试以下内容:

ScrollView() {
    ForEach(elements) { element in
        CellView(element: element)
        Divider()
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接