我的 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)

编辑: 我的整个视图 struct 如下:

NavigationStack { 
    ZStack {
        Color.backgroundColor
            .ignoresSafeArea()

        VStack {
            // some other stuff
            List {
                // my list from above
            }
        }
    }
}

问题是,当My List为空时,将有一个黑色背景,而不是我的自定义背景 colored颜色 ,后者在填充List时存在.

Empty List

Populated List

推荐答案

这看起来像是百年虫,但首先:

您在List上使用的是listRowBackground修改量,而不是background,并且没有行到背景!改成background.

List(viewModel.exerciseSelection, id: \.id) { exercise in
   ,,,
}
.listStyle(.plain)
.scrollContentBackground(.hidden)
.background(Color.backgroundColor) // ? 1 absolute issue was here

然后,您可以退回到UIScrollView:

init() {
    UIScrollView.appearance().backgroundColor = .clear
}

2.

或者通过opacity修改器隐藏整个List,以防止分支和布局问题以及不必要的重新渲染,如下所示:

List(...) { ... }
.opacity(viewModel.exerciseSelection.isEmpty ? 0 : 1)

3.

或者,您也可以使用LazyVStack:

ScrollView {
    LazyVStack {
        ForEach(viewModel.exerciseSelection, id: \.self) { exercise in ... }
    }
}

Swift相关问答推荐

从Swift中的泛型类继承?

Swift 扩展:通过方法重载增强现有类

Xcode 15 Beta中如何使用@Observable?

避免 `(())` 显式指定 Void 类型的枚举关联值

如何自己实现同一个 iOS 16 锁屏圆形小部件?

为什么 id 不能通过 struct 从 Objective-C 移植到 Swift?

动画偏移正在 destruct 按钮 SwiftUI

如何在 SwiftUI 中用图像替换占位符文本?

Swift 中的Combine和didSet有什么区别?

与 SwiftUI 中的 onChange 修饰符相比,objectWillChangeSequence 的目的是什么?

SwiftUI:异步网络请求后@State 值不更新

引用类型(类)不需要但 struct 需要的可识别 id

SwiftUI Observed Object 在发布值更改时未更新

使用 Date.ParseStrategy 将字符串解析为日期

用于 Swift 编码的 iOS 应用程序的 Ffmpeg

iOS Swift - 如何更改表格视图的背景 colored颜色 ?

Swift 中惰性 var 的优势是什么

URLComponents.url 为零

Swift 中的可选数组与空数组

ISO8601DateFormatter 不解析 ISO 日期字符串