You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中如何为列表行SwipeActions自定义按钮样式

解决SwiftUI SwipeActions自定义按钮不显示的问题

核心原因

SwiftUI的SwipeActions默认会对内部按钮应用系统样式,强制替换文本为默认的“Delete”并覆盖自定义视图,导致自定义UI无法正常显示。

可行解决方案

方案1:取消系统默认按钮样式

在SwipeActions内的Button中使用自定义视图,并通过.buttonStyle(.plain)关闭系统默认样式,让自定义UI完全生效:

List {
    ForEach(items) { item in
        Text(item.name)
            .swipeActions(edge: .trailing) {
                Button(role: .destructive) {
                    // 执行删除逻辑
                    deleteItem(item)
                } label: {
                    CellDeleteButton() // 你的自定义按钮视图
                }
                .buttonStyle(.plain) // 关键:取消系统默认样式
            }
    }
}

方案2:适配自定义视图尺寸

如果自定义视图仍不显示,可能是尺寸未适配SwipeAction容器,给自定义视图添加尺寸约束:

struct CellDeleteButton: View {
    var body: some View {
        HStack(spacing: 8) {
            Image(systemName: "trash.fill")
                .foregroundColor(.white)
            Text("删除")
                .foregroundColor(.white)
        }
        .frame(width: 90, height: .infinity) // 适配SwipeAction的高度
        .background(Color.red)
    }
}

注意事项

  • 保留role: .destructive可维持系统滑动交互的一致性,不会影响自定义UI显示
  • 无需保留默认的Text("Delete")标签,直接替换为自定义视图即可
  • 确保自定义视图的背景色、内容颜色与场景适配,避免被系统样式覆盖

完整验证示例

struct Item: Identifiable {
    let id = UUID()
    let name: String
}

struct ContentView: View {
    @State private var items = [Item(name: "项目1"), Item(name: "项目2"), Item(name: "项目3")]
    
    func deleteItem(_ item: Item) {
        if let index = items.firstIndex(where: { $0.id == item.id }) {
            items.remove(at: index)
        }
    }
    
    var body: some View {
        List {
            ForEach(items) { item in
                Text(item.name)
                    .swipeActions(edge: .trailing) {
                        Button(role: .destructive) {
                            deleteItem(item)
                        } label: {
                            CellDeleteButton()
                        }
                        .buttonStyle(.plain)
                    }
            }
        }
    }
}

struct CellDeleteButton: View {
    var body: some View {
        HStack(spacing: 8) {
            Image(systemName: "trash.fill")
            Text("删除")
        }
        .foregroundColor(.white)
        .frame(width: 90, height: .infinity)
        .background(Color.red)
    }
}

内容的提问来源于stack exchange,提问作者DevChris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 20:22:07