【问题标题】:Is there a way to change the background of List rows in SwiftUI? [duplicate]有没有办法改变 SwiftUI 中列表行的背景? [复制]
【发布时间】:2019-12-01 02:21:43
【问题描述】:

我想在 SwiftUI 中更改 List 行的背景颜色,但不太清楚。这是迄今为止我编写的代码的一个更简单的版本。

struct ContentView: View {
    init() {
        UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.black]
        UINavigationBar.appearance().barTintColor = .blue
    }
    
    var body: some View {
        NavigationView {
            ZStack {
                HStack {
                    List(0...10) { test in
                        Spacer()
                            self.background(Color.purple)
                        Text("This is a test")
                        Spacer()
                        self.background(Color.pink)
                    }
                    .background(Color.blue)
                    List(0...10) { test2 in
                        Spacer()
                        Text("Also a test")
                            .background(Color.green)
                        Spacer()
                    }
                    .background(Color.red)
                }
            }
        }
        .navigationBarTitle(
            Text("Test"),
            displayMode: .inline
        )
    }
}

我只想改变单元格/行背景的颜色,但它们在浅色模式下保持白色,在深色模式下保持黑色。

【问题讨论】:

标签: swift swiftui


【解决方案1】:

您可以为此使用.colorMultiply() 属性,

针对 XCode 11 更新了代码。

检查下面的代码:

init() {
        UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.black]
        UINavigationBar.appearance().barTintColor = .blue
    }

    var body: some View {

    NavigationView {
        VStack {
            HStack {
                List(0..<10) { test1 in
                    Spacer()
                    Text("This is a test1")
                    Spacer()
                }.colorMultiply(Color.pink)

                List(0..<10) { test2 in
                    Spacer()
                    Text("This is a test2")
                        .background(Color.green)
                    Spacer()
                }.colorMultiply(Color.green)
            }.padding(.top)
        }.navigationBarTitle(Text("Test"), displayMode: .inline)
    }

}

输出:

【讨论】:

  • 现在在 XCode 11 中不起作用。在我的情况下,颜色应用于文本,无论我做什么我都无法设置行本身的背景颜色,在调试视图层次结构时似乎被称为“UIItemHostingView”
  • @Simon 你在检查 XCode 11 Beta 4 吗?
  • @KetanOdedra 我没有,因为 XCode 11 已发布。我本来打算写“现在不能在稳定的 XCode 11 中工作。”,但显然我跳过了那个重要的细节哈哈......
  • @Simon 现在代码已针对 XCode 11 进行了更新。
  • @KetanOdedra 它现在确实以某种方式改变了背景,但不能以某种方式使用它。除了它破坏了 NavigationView 的事实之外,列表位于内部(标题与第一个元素重叠)。这发生在预览版和设备/模拟器上。
【解决方案2】:

我发现使用列表和部分的一件事是它们是 tupleview 类型,即它们不是单个视图,并且诸如border() 和 background() 之类的内容适用于列表内的元素,而不是列表本身。要创建单个视图进行修改,您需要将它们嵌入到堆栈中。

【讨论】:

    猜你喜欢
    • 2020-11-12
    • 2021-12-22
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多