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

前端 未结 13 1745
盖世英雄少女心
盖世英雄少女心 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:48

    IOS 14

    There is currently no solution to hide the separators on the IOS 14 beta.

    If you don't need an editable List, you should use a LazyVStack inside a ScrollView.

    But if you want to stay on the List. I found a solution on the Apple forum by samwarner. https://developer.apple.com/forums/thread/651028

    This is a temporary solution. In some cases you may need to adjust the insets. Here is its implementation:

    struct HideRowSeparatorModifier: ViewModifier {
        static let defaultListRowHeight: CGFloat = 44
        var insets: EdgeInsets
        var background: Color
        
        init(insets: EdgeInsets, background: Color) {
            self.insets = insets
            var alpha: CGFloat = 0
            UIColor(background).getWhite(nil, alpha: &alpha)
            assert(alpha == 1, "Setting background to a non-opaque color will result in separators remaining visible.")
            self.background = background
        }
        
        func body(content: Content) -> some View {
            content
                .padding(insets)
                .frame(
                    minWidth: 0, maxWidth: .infinity,
                    minHeight: Self.defaultListRowHeight,
                    alignment: .leading
                )
                .listRowInsets(EdgeInsets())
                .background(background)
        }
    }
    
    extension EdgeInsets {
        static let defaultListRowInsets = Self(top: 0, leading: 16, bottom: 0, trailing: 16)
    }
    
    extension View {
        func hideRowSeparator(insets: EdgeInsets = .defaultListRowInsets, background: Color = .white) -> some View {
            modifier(HideRowSeparatorModifier(insets: insets, background: background))
        }
    }
    

    Finally, here is the implementation on a list. You have to add .hideRowSeparator() on the list cell.

    struct CustomRow: View {
        let text: String
        
        var body: some View {
            HStack {
                Text(self.text)
                Image(systemName: "star")
            }
        }
    }
    
    struct ContentView : View {
        @State private var fruits = ["Apple", "Orange", "Pear", "Lemon"]
        
        var body: some View {
            VStack(alignment: .leading) {
                List {
                    ForEach(self.fruits, id: \.self) { str in
                        CustomRow(text: str)
                            .hideRowSeparator()
                    }
                }
            }
            .padding(.top)
        }
    }
    
    0 讨论(0)
提交回复
热议问题