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

SwiftUI空List背景显示黑色而非自定义背景色问题求助

问题描述

List组件在数据为空时背景显示为黑色,无法正常展示自定义背景色;但当List有数据时,自定义背景色能正常渲染。

相关代码

List实现代码

List(viewModel.exerciseSelection, id: \.id) { exercise in
    AddWorkoutDetailView(exerciseName: exercise.name, gifImage: exercise.gifUrl)
        .listRowInsets(EdgeInsets())
        .listRowBackground(Color.backgroundColor)
        .swipeActions(allowsFullSwipe: false) {
            Button(role: .destructive) {
                                
            } label: {
                Label("Delete", systemImage: "trash.fill")
            }
        }
}
.listStyle(.plain)
.scrollContentBackground(.hidden)
.listRowBackground(Color.backgroundColor)

完整View结构

NavigationStack { 
    ZStack {
        Color.backgroundColor
            .ignoresSafeArea()

        VStack {
            // 其他业务内容
            List {
                // 上述List代码
            }
        }
    }
}

现象说明

  • 空List状态:背景呈现黑色
  • 有数据List状态:自定义背景色正常显示

解决方案

方案一:添加空状态占位视图

修改List的实现,在数据为空时添加一个与全局背景色一致的占位视图,填充整个List空间:

List {
    ForEach(viewModel.exerciseSelection, id: \.id) { exercise in
        AddWorkoutDetailView(exerciseName: exercise.name, gifImage: exercise.gifUrl)
            .listRowInsets(EdgeInsets())
            .listRowBackground(Color.backgroundColor)
            .swipeActions(allowsFullSwipe: false) {
                Button(role: .destructive) {
                            
                } label: {
                    Label("Delete", systemImage: "trash.fill")
                }
            }
    }

    // 空状态占位,覆盖List空容器区域
    if viewModel.exerciseSelection.isEmpty {
        Color.backgroundColor
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .listRowInsets(EdgeInsets())
            .listRowBackground(Color.backgroundColor)
    }
}
.listStyle(.plain)
.scrollContentBackground(.hidden)

方案二:让List背景透明

利用外层ZStack已有的全局背景,将List的背景设置为透明,空List时直接透出底层颜色:

List(viewModel.exerciseSelection, id: \.id) { exercise in
    AddWorkoutDetailView(exerciseName: exercise.name, gifImage: exercise.gifUrl)
        .listRowInsets(EdgeInsets())
        .listRowBackground(Color.backgroundColor)
        .swipeActions(allowsFullSwipe: false) {
            Button(role: .destructive) {
                                
            } label: {
                Label("Delete", systemImage: "trash.fill")
            }
        }
}
.listStyle(.plain)
.scrollContentBackground(.hidden)
.background(Color.clear) // 空List时透出ZStack的背景色

问题根源

当List无数据时,系统会默认渲染一个空容器视图,该容器的背景色为系统深色(黑色),即使设置了scrollContentBackground(.hidden)也无法覆盖这个默认背景。通过上述两种方式,要么用同色占位覆盖空容器,要么让List背景透明透出外层全局背景,就能解决空List背景变黑的问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 11:38:17