How to remove the line separators from a List in SwiftUI without using ForEach?

前端 未结 13 1793
盖世英雄少女心
盖世英雄少女心 2021-01-30 04:50

I have this code to display a list of custom rows.

struct ContentView : View {
    var body: some View {
        VStack(alignment: .leading) {
            List(1         


        
13条回答
  •  暖寄归人
    2021-01-30 05:23

    This is my extension ListRowExtensions for hide list row separator and custom this one.

    import SwiftUI
    
    // MARK: List row extensions
    
    extension View {
        
        func hideListRowSeparator() -> some View {
            return customListRowSeparator(insets: .init(), insetsColor: .clear)
        }
        
        func customListRowSeparator(
            insets: EdgeInsets,
            insetsColor: Color) -> some View {
            modifier(HideRowSeparatorModifier(insets: insets,
                                              background: insetsColor
            )) .onAppear {
                UITableView.appearance().separatorStyle = .none
                UITableView.appearance().separatorColor = .clear
            }
        }
    }
    
    // MARK: ViewModifier
    
    private struct HideRowSeparatorModifier: ViewModifier {
            
        var insets: EdgeInsets
        var background: Color
        
        func body(content: Content) -> some View {
            content
                .padding(insets)
                .frame(
                    minWidth: 0,
                    maxWidth: .infinity,
                    maxHeight: .infinity,
                    alignment: .leading
                )
                .listRowInsets(EdgeInsets())
                .background(background)
        }
    }
    

    Use :

    // Without list row separator
    List {
        ForEach(self.viewModel.data, id: \.id) { item in
            Text("Text")
        }
        .hideRowSeparatorItemList()
    }
    
    // With list row separator with color and size
    List {
        ForEach(self.viewModel.data, id: \.id) { item in
            Text("Text")
        }
        .customListRowSeparator(insets: EdgeInsets(top: 0,
                                                   leading: 0,
                                                   bottom: 5,
                                                   trailing: 0),
                                insetsColor: Color.red)
    }
    

提交回复
热议问题