如何在SwiftUI中修改列表的背景色?

and*_*ive 17 swift swiftui

我正在尝试重新创建使用SwiftUI中的UIKit构建的UI,但是遇到了一些小问题。

我想要更改List此处的颜色,但是没有任何属性像我期望的那样起作用。下面的示例代码:

struct ListView: View {
    @EnvironmentObject var listData: ListData

       var body: some View {
        NavigationView {
            List(listData.items) { item in
                ListItemCell(item: item)
            }
            .content.background(Color.yellow) // not sure what content is defined as here
            .background(Image("paper-3")) // this is the entire screen 
        }
    }
}

struct ListItemCell: View {
    let item: ListItem

    var body: some View {

        NavigationButton(destination: Text(item.name)) {
            Text("\(item.name) ........................................................................................................................................................................................................")
                .background(Color.red) // not the area I'm looking for
        }.background(Color.blue) // also not the area I'm looking for
    }
}
Run Code Online (Sandbox Code Playgroud)

我想更改白色区域

Jor*_*n H 40

iOS 16 提供了一个修饰符来控制 List(和其他可滚动视图)的背景可见性:scrollContentBackground(_:)

您可以通过隐藏标准系统背景.hidden。如果您background也提供了 a,它将变得可见。

List {
    Text("One")
    Text("Two")
}
.background(Image("MyImage"))
.scrollContentBackground(.hidden)
Run Code Online (Sandbox Code Playgroud)

您可能还想自定义列表行的背景 - 各个单元格 - 和分隔符。这可以像这样完成:

List {
    Section("Header") {
        Text("One")
        Text("Two")
            .listRowBackground(Color.red)
    }
    .listRowBackground(Color.clear)
    .listRowSeparator(.hidden)
}
.scrollContentBackground(.hidden)
Run Code Online (Sandbox Code Playgroud)


小智 38

这会将整个列表的背景设置为绿色:

init() {
   UITableView.appearance().separatorStyle = .none
   UITableViewCell.appearance().backgroundColor = .green
   UITableView.appearance().backgroundColor = .green
}
Run Code Online (Sandbox Code Playgroud)

  • 我如何在不同的列表中改变这一点?我将其应用于一个选项卡中的一个列表,这会影响另一个选项卡视图中的另一个列表。 (12认同)
  • @glothais-kwl,您可以使用 `UIAppearance.appearanceWhenContainedInInstancesOfClasses:` 并传递 `UIHostingController` 的特定子类,您将使用它来呈现这个确切的 SwiftUI 视图。 (3认同)

Vis*_*tel 28

您可以通过更改UITableView的外观来实现。

UITableView.appearance().backgroundColor = UIColor.clear
Run Code Online (Sandbox Code Playgroud)

只需将这一行放在AppdelegatedidFinishLaunchingWithOptions方法中。在替换UIColor.clear设置任何您想要添加到list.

  • 它完成这项工作: UITableViewCell.appearance().backgroundColor = .clear (4认同)

And*_*rew 18

2022年

苹果系统解决方案

以下代码使 ALL OFList的背景颜色透明:

// Removes background from List in SwiftUI
extension NSTableView {
    open override func viewDidMoveToWindow() {
        super.viewDidMoveToWindow()
        
        backgroundColor = NSColor.clear
        if let esv = enclosingScrollView {
            esv.drawsBackground = false
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

…………

…………

…………

以下代码使所有TextEditor背景颜色透明:

extension NSTextView {
    open override var frame: CGRect {
        didSet {
            backgroundColor = .clear
            drawsBackground = true
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 惊人的!SwiftUI 应该将其设为默认值,哈哈 (2认同)

小智 12

我能够通过使用 colorMultiply(Color:) 来改变整个列表的颜色。只需将此修饰符添加到列表视图的末尾,然后填充会将表格推到设备边缘。例如:

List {...}.colorMultiply(Color.green).padding(.top)
Run Code Online (Sandbox Code Playgroud)

https://www.hackingwithswift.com/quick-start/swiftui/how-to-adjust-views-by-tinting-and-desaturating-and-more

  • 它有效,但它与单元格的颜色混淆 - 即刚刚尝试使用红色文本作为列表项 - 它们变成黑色。 (9认同)

Mar*_*dal 12

好的,我找到了为列表行着色的解决方案:

struct TestRow: View {

    var body: some View {
        Text("This is a row!")
        .listRowBackground(Color.green)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在体内:

List {
    TestRow()
    TestRow()
    TestRow()
}
Run Code Online (Sandbox Code Playgroud)

这按我的预期工作,但是我还没有找到如何删除行之间的分隔线的方法。

  • SwiftUI现在是令人难以置信的错误,当我使用这样的代码并对列表项进行硬编码时,它会起作用。当我异步加载数据时,它不再起作用。 (5认同)
  • @andromedainiative Do List { ForEach(items, id: \.self) { item in Text(item).listRowBackground(Color.green) } 相反,然后它就可以工作了。 (4认同)
  • 是的,有点痛苦。玩起来很有趣。希望很快会更加顺利 (2认同)
  • @MariusWaldal 您找到如何更改剖面视图背景颜色了吗? (2认同)

小智 11

SwiftUI中有一个说法:listRowBackground(),但是如果直接用List来迭代数据集合,是不行的。

这是我的解决方法:

    List {
        // To make the background transparent, we have we use a ForEach as a wrapper
        ForEach(files) {file in
            Label(
                title: { Text(file.name ?? fileOptionalFiller).lineLimit(listRowTextLineLimit) },
                icon: { AppIcon.doc.foregroundColor(.primary) }
            )
        }
        .listRowBackground(Color.primary.colorInvert())
    }
Run Code Online (Sandbox Code Playgroud)

基本上,如果您在 List 中使用 ForEach,则 listRowBackground() 会起作用。


Mus*_*han 8

我不知道连接是什么,但如果你用Form它包装列表,它就可以工作。

Form {
     List(viewModel.currencyList, id: \.self) { currency in
        ItemView(item: currency)
     }
      .listRowBackground(Color("Primary"))
      .background(Color("Primary"))
}
Run Code Online (Sandbox Code Playgroud)

  • 正如 Caleb 指出的那样,listRowBackground 不应应用于列表,而应应用于行项目本身。另外,您应该能够只执行 Color("Primary") 而不是强制展开 UIColor :) (4认同)

小智 7

struct Details: View {

    var body: some View {
        Spacer().overlay(
            List {
                Text("Hello World!").font(.title2)
                    .listRowBackground(Color.clear)
                Text("Hello World again").font(.title2)
                    .listRowBackground(Color.clear)
            }.onAppear() {
                UITableView.appearance().backgroundColor = UIColor.green
                UITableViewCell.appearance().backgroundColor = UIColor.green
            }
        )
    }
}
Run Code Online (Sandbox Code Playgroud)


cha*_*l-f 7

Islom Alimov /sf/answers/4197926561/的答案在我看来似乎是迄今为止最好的实现。

唯一的缺点:这也会更改应用程序中所有其他列表视图的背景颜色,因此您需要手动将它们更改回来,除非您希望到处都具有相同的颜色。

这是一个示例视图:

import SwiftUI

struct TestView1: View {
    
    init(){
        UITableView.appearance().backgroundColor = UIColor(Color.clear)
    }
    
    @State var data = ["abc", "def"]
    
    var body: some View {
        VStack {
            List {
                ForEach(data, id: \.self) {element in
                    Text("\(String(describing: element))")
                }
                .background(Color.green)
                .listRowBackground(Color.blue)
                
            }
            .background(Color.yellow)
            Spacer()
            Color.red
        }
    }
}

struct TestView1_Previews: PreviewProvider {
    static var previews: some View {
        TestView1()
    }
}
Run Code Online (Sandbox Code Playgroud)

产生:


小智 6

.listRowBackground如果尝试使用 SwiftUI 使用和应用创建浮动类型单元格,有人可能会发现这很有用.padding

var body: some View {
    NavigationView {
        List {
            ForEach (site) { item in
                HStack {
                    Text(String(item.id))

                    VStack(alignment: .leading) {
                        Text(item.name)
                        Text(item.crop[0])
                    }

                }.listRowBackground(Color.yellow)
                      .padding(.trailing, 5)
                      .padding(.leading, 5)
                      .padding(.top, 2)
                      .padding(.bottom, 2))
            }
        }
            .navigationBarTitle(Text("Locations"))
    }
}
Run Code Online (Sandbox Code Playgroud)


Seu*_*Ham 6

在此处输入图片说明

struct ContentView: View {

    var strings = ["a", "b"]

    var body: some View {

        List {
            ForEach(strings, id: \.self) { string in
                Text(string)
            }.listRowBackground(Color.green)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这也是唯一对我有用的方法。我认为重要的是要强调,您必须使用“List { ForEach(elements) { }}”而不是“List(elements) { }”才能使此修饰符起作用。 (18认同)
  • 疯狂的是,您将数据指定到列表的方式使该修饰符不起作用。看到其中的此类错误,并不会在 SwiftUI 整体上留下良好的印象。 (4认同)
  • 唯一可行的方法 (2认同)
  • 此问题已在 iOS 15 中修复。 `listRowBackground` 适用于 `List(elements)` 以及 `List { ForEach(elements) {` 中的项目 (2认同)

小智 5

更改背景颜色

正如其他人提到的,更改 UITableView 背景将影响您应用程序中的所有其他列表。

但是,如果您想要不同的背景颜色,您可以将默认值设置为clear,并在 swiftui 视图中设置背景颜色,如下所示:

List {
    Text("Item 1")
    Text("Item 2")
    Text("Item 3")
}
// Ignore safe area to take up whole screen
.background(Color.purple.ignoresSafeArea())
.onAppear {
    // Set the default to clear
    UITableView.appearance().backgroundColor = .clear
}
Run Code Online (Sandbox Code Playgroud)

您可能希望更早地设置 tableview 外观,例如在SceneDelegate或根视图中,如下所示:

// SceneDelegate
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
      
    
    guard let windowScene = scene as? UIWindowScene else {
        print("Returning because screne does not exist")
        return
            
    }
    
    // Set here    
    UITableView.appearance().backgroundColor = .clear
    let contentView = ContentView()
    let window = UIWindow(windowScene: windowScene)
    window.rootViewController = UIHostingController(rootView: contentView)
    self.window = window
    window.makeKeyAndVisible()
}


// Root App View
@main
struct ListBackgroundApp: App {
    
    init() {
        UITableView.appearance().backgroundColor = .clear
    }
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

工作背景颜色变化