SwiftUI:如何在列表上实现渐变背景

12

有人能告诉我如何在SwiftUI列表中添加渐变背景吗?

当前代码:

struct TestView: View {
    var body: some View {
        LinearGradient(gradient: Gradient(colors: [Color.red, Color.purple]), startPoint: .top, endPoint: .bottom)
            .edgesIgnoringSafeArea(.vertical)
            .overlay(
                List {
                    Group {
                        Text("Hallo")
                        Text("World")
                    }
                    .background(Color.blue)
                }
                .background(Color.green)
                .padding(50)
        )
    }
}

当前的布局是,渐变色在单元格后面显示。我希望使单元格透明以便看到下方的渐变色。

输入图像描述

谢谢!

1个回答

18

你已经添加了渐变。只需将背景颜色设置为透明,并摆脱那些测试代码 ;)

iOS 16

您可以使用scrollContentBackground(.hidden)修饰符隐藏任何可滚动内容的背景

iOS 15及以下版本

您应该使用UITableViewUITableViewCellappearance属性隐藏默认列表背景和所有单元格。

还可以使用.listRowBackground(.clear)隐藏单元格背景。

示例

struct TestView: View {

    init() {
        UITableView.appearance().backgroundColor = .clear
        UITableViewCell.appearance().backgroundColor = .clear
    }
    
    var body: some View {
        LinearGradient(gradient: Gradient(colors: [Color.red, Color.purple]), startPoint: .top, endPoint: .bottom)
            .edgesIgnoringSafeArea(.vertical)
            .overlay(
                List {
                    Group {
                        Text("Hallo")
                        Text("World")
                    }
                }
                .padding(50)
        )
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接