Home > Software design >  SwiftUI Custom List Cell - disable horizontal padding/shrink in EditMode
SwiftUI Custom List Cell - disable horizontal padding/shrink in EditMode

Time:05-09

I'm trying to create a custom List cell in SwiftUI, where the drag-icon in Edit Mode stays inside the cell.

By default, the cell gets horizontally shrinked do make space for the drag handle and delete button, as soon as the list enters Edit Mode.

Actually adding a listRowBackground could do the trick, but then I'm not able to add cornerRadius and padding anymore.

What happens right now:

What happens right now:

Desired behaviour:

Desired behaviour:

Does anyone know a trick or solution with introspect how to achieve that?

Example Code:

struct ListInList: View {

    @State var datas = ["Row 1", "Row 2", "Row 3"]

    var body: some View {
        NavigationView{
            List{
            
                ForEach(datas, id: \.self) { data in
                    HStack{
                        Text(data)
                            .frame(maxWidth: .infinity)
                            .padding()
                    }
                    .listRowSeparator(.hidden)
                    .listRowInsets(EdgeInsets())
                    .listRowBackground(Color.clear)
                    .ignoresSafeArea(edges: .horizontal)
                    .background(Color.gray.opacity(0.3))
                    .cornerRadius(10)
                    .deleteDisabled(true)
                    .padding(EdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16))
                }
                .onMove(perform: move)
            }
            .listStyle(.plain)
            .toolbar{
                ToolbarItem(placement: .navigationBarTrailing){
                    EditButton()
                }
            }
        }
    }

    func move(from source: IndexSet, to destination: Int) {
        datas.move(fromOffsets: source, toOffset: destination)
    }
}

CodePudding user response:

Ok, I figured it out by myself. I totally forgot, that .listRowBackground() can receive a View.

enter image description here

So for everyone facing the same Problem:

    List{
        ForEach(datas, id: \.self) { data in
            HStack{
                Text(data)
                    .padding(.vertical,20)
            }
            .listRowSeparator(.hidden)
            .listRowBackground(
                Color.gray.opacity(0.3)
                    .cornerRadius(10)
                    .padding(.vertical, 8)
                )
        }
        .onMove(perform: move)
    }
    .padding(.horizontal)
    .listStyle(.plain)
  • Related