如何在进行滑动删除操作时保持自定义视图背景静态

问题描述 投票:0回答:1

所以我有这个代码:

struct ContentView: View {
    @State private var names = ["Ted", "Barney", "Lily", "Robin", "Marshal"]

    var body: some View {
        List {
            ForEach(names, id: \.self) { name in
                ListRowView(name: name)
            }
            .onDelete(perform: deleteName)
        }
        .listStyle(.plain)
        .scrollContentBackground(.hidden)
    }

    func deleteName(at offsets: IndexSet) {
        names.remove(atOffsets: offsets)
    }
}

struct ListRowView: View {

    let name: String

    var body: some View {
        HStack {
            iconView
            titleView
            Spacer()
        }
        .background(
            RoundedRectangle(cornerRadius: 20)
                .fill(.purple)
        )
    }

    var titleView: some View {
        Text("\(name)")
            .foregroundStyle(.white)
    }


    var iconView: some View {
        Circle()
            .fill(Color.white.opacity(0.2))
            .frame(width: 80, height: 80)
            .padding()
    }
}

当我滑动删除时,它看起来像这样:

但我正在努力实现这样的目标:

我希望滑动时从右侧出现的红色视图成为行背景的一部分。我不知道如何更好地解释它。也许我以错误的方式应用背景视图?

ios swift swiftui
1个回答
0
投票

使用原生 api 可以实现的最接近的事情是使用

Section
insetGrouped
样式列表的组合:

Demo

List {
    ForEach(names, id: \.self) { name in
        Section { // 👈 Separate cells
            ListRowView(name: name)
        }
    }
    .onDelete(perform: deleteName)
    .listRowBackground(Color.purple) /// 👈 Use a simple background color
    .listRowInsets(.init()) // 👈 Fit the content to the edges of the cell
    .listSectionSpacing(16) // 👈 Nicer spacing
}
.listStyle(.insetGrouped) // 👈 Make the sections appear rounded
.scrollContentBackground(.hidden)
© www.soinside.com 2019 - 2024. All rights reserved.