繁体   English   中英

如何修改SwiftUI中List的背景色?

[英]How do I modify the background color of a List in 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
    }
}

我想改变白色区域

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

struct TestRow: View {

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

然后在正文中:

List {
    TestRow()
    TestRow()
    TestRow()
}

这可以按我的预期工作,但我还没有弄清楚如何删除行之间的分隔线......

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

init() {
   UITableView.appearance().separatorStyle = .none
   UITableViewCell.appearance().backgroundColor = .green
   UITableView.appearance().backgroundColor = .green
}

在此处输入图像描述

struct ContentView: View {

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

    var body: some View {

        List {
            ForEach(strings, id: \.self) { string in
                Text(string)
            }.listRowBackground(Color.green)
        }
    }
}

您可以通过更改UITableView的外观来做到这一点。

UITableView.appearance().backgroundColor = UIColor.clear

只需将此行放在AppdelegatedidFinishLaunchingWithOptions方法中。 代替UIColor.clear设置要在list的背景颜色中添加的任何颜色。

更改背景颜色

正如其他人所提到的,更改 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
}

您可能希望更早地设置 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()
        }
    }
}

工作背景颜色变化

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())
    }

基本上,如果您在 List 中使用 ForEach,则 listRowBackground() 可以工作。

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

List {...}.colorMultiply(Color.green).padding(.top)

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

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

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

2022,MacOS 解决方案

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

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

在此处输入图像描述

…………

…………

…………

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

extension NSTextView {
    open override var frame: CGRect {
        didSet {
            backgroundColor = .clear
            drawsBackground = true
        }
    }
}
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
            }
        )
    }
}

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

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"))
    }
}

Islom Alimov https://stackoverflow.com/a/59970379/9439097的答案在我看来似乎是迄今为止最好的实现。

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

这是一个示例视图:

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()
    }
}

产生:

我认为listRowPlatterColor修饰符应该这样做,但不是 Xcode 11 Beta 11M336w

var body: some View {
    List(pokemon) { pokemon in
        PokemonCell(pokemon: pokemon)
            .listRowPlatterColor(.green)
    }
}

对我来说,在 SwiftUI 中更改 List 背景的完美解决方案是:

struct SomeView: View {
    init(){
    UITableView.appearance().backgroundColor = UIColor(named: "backgroundLight")
      }
...

}

列表还不完善。

一个选项是像这样使用它 -> List { ForEach(elements) { }}而不是List($elements)

就我而言,这是迄今为止效果最好的。 就像@FontFamily 所说,它不应该破坏任何List默认行为,如滑动。

.colorMultiply(...)

作为一个选项,您可以.colorMultiply(Color.yourColor)修饰符。

警告这不会改变颜色! 这只Multiply修改器应用于当前颜色。 请在采取任何行动之前阅读问题,因为您可能正在寻找:“如何在 SwiftUI 中更改列表的背景颜色”,这对您不起作用。 ❄️

例子:

List (elements, id:\.self ) { element in

     Text(element)

}
.colorMultiply(Color.red) <--------- replace with your color

在此处输入图像描述

只需在init()方法中添加UITableView外观背景颜色并添加列表样式(.listStyle(SidebarListStyle()) 。不要忘记导入UIKit模块

struct HomeScreen: View {
init() {
    UITableView.appearance().backgroundColor = .clear
}

let tempData:[TempData] = [TempData( name: "abc"),
                         TempData( name: "abc"),
                         TempData( name: "abc"),
                         TempData( name: "abc")]

var body: some View {
    ZStack {
        Image("loginBackgound")
            .resizable()
            .scaledToFill()
        List{
            ForEach(tempData){ data in
                Text(data.name)
            }
        }
        .listStyle(SidebarListStyle())
        
    }
    .ignoresSafeArea(edges: .all)
}
}

如果要避免全局设置所有表视图的外观,可以将UITableView.appearance(whenContainedInInstancesOf:)UIHostingController结合使用。 感谢DanSkeel您在上面留下的评论指出了这一点。 这就是我使用它的方式:

public class ClearTableViewHostingController<Content>: UIHostingController<Content> where Content: View {
    public override func viewDidLoad() {
        UITableView.appearance(whenContainedInInstancesOf: [ClearTableViewHostingController<Content>.self]).backgroundColor = .clear
    }
}

您可以像这样使用ClearTableViewHostingController

let view = MyListView()
let viewController = ClearTableViewHostingController(coder: coder, rootView: view)

然后在您的视图中,您可以像这样设置列表背景颜色:

List {
    Text("Hello World")
}
.background(Color.gray)

使扩展列表如下:

extension List{
@available(iOS 14, *)
func backgroundList(_ color: Color = .clear) -> some View{
    UITableView.appearance().backgroundColor = UIColor(color)
    return self
}

}

使用UITableView.appearance().backgroundColor不是一个好主意,因为它会更改所有表格的背景颜色。 我在您在iOS 14, 15中选择的确切表格上找到了一个可行的颜色更改解决方案。

我们将使用需要在列表中应用的修饰符来更改颜色

extension View {
    
    func backgroundTableModifier(_ color: UIColor? = nil) -> some View {
        self.modifier(BackgroundTableModifier(color: color))
    }

}

我们的任务是找到 UITableView,然后更改颜色。

private struct BackgroundTableModifier: ViewModifier {
    
    private let color: UIColor?
    @State private var tableView: UITableView?
    
    init(color: UIColor?) {
        self.color = color
    }
    
    public func body(content: Content) -> some View {
        if tableView?.backgroundColor != color {
            content
                .overlay(BackgroundTableViewRepresentable(tableBlock: { tableView in
                    tableView.backgroundColor = color
                    self.tableView = tableView
                }))
        } else {
            content
        }
    }
}

private struct BackgroundTableViewRepresentable: UIViewRepresentable {
    
    var tableBlock: (UITableView) -> ()
    
    func makeUIView(context: Context) -> BackgroundTableView  {
        let view = BackgroundTableView(tableBlock: tableBlock)
        return view
    }
    
    func updateUIView(_ uiView: BackgroundTableView, context: Context) {}
}

class BackgroundTableView: UIView {
    
    var tableBlock: (UITableView) -> ()
    
    init(tableBlock: @escaping (UITableView) -> ()) {
        self.tableBlock = tableBlock
        super.init(frame: .zero)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        if let tableView = findTableView(in: self) {
            tableBlock(tableView)
        }
    }
    
    private func findTableView(in view: UIView) -> UITableView? {
        if let tableView = view as? UITableView {
            return tableView
        }
        
        if let superView = view.superview {
            return findTableView(in: superView)
        }
        
        return nil
    }
    
}

为了找到 UITableView,修饰符必须在 List 内。 自然,您需要确保只调用一次修饰符,而不需要将其应用于每一行。 这是一个使用示例

List {
   rows()
     .backgroundTableModifier(.clear)
}

func rows() -> some View {
    ForEach(0..<10, id: \.self) { index in
        Row()
    }
}

我启发了一些用于配置每页 NavigationView 导航栏样式的配置器,并编写了一些简单的 UITableView 每页配置器不使用 UITableView.appearance() 全局方法

   import SwiftUI

    struct TableViewConfigurator: UIViewControllerRepresentable {

        var configure: (UITableView) -> Void = { _ in }

        func makeUIViewController(context: UIViewControllerRepresentableContext<TableViewConfigurator>) -> UIViewController {

            UIViewController()
        }

        func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<TableViewConfigurator>) {

            let tableViews = uiViewController.navigationController?.topViewController?.view.subviews(ofType: UITableView.self) ?? [UITableView]()

            for tableView in tableViews {
                self.configure(tableView)
            }
        }
    }

然后需要 UIView 扩展来查找所有 UITableViews

extension UIView {
    func subviews<T:UIView>(ofType WhatType:T.Type) -> [T] {
        var result = self.subviews.compactMap {$0 as? T}
        for sub in self.subviews {
            result.append(contentsOf: sub.subviews(ofType:WhatType))
        }
        return result
    }
}

最后的用法是:

List {

}.background(TableViewConfigurator {
    $0.backgroundColor = .red
})

也许应该改进一件事,即使用 navigationController?.topViewController 使其即使在视图控制器层次结构中没有 navigationController 也能工作

如果有人来这里寻找 iPhone X/11 上横向背景而不是全宽的解决方案,请尝试:

.listRowBackground(Color("backgroundColour").edgesIgnoringSafeArea(.all))

您可以使用 Github 中的introspect库为基础表视图设置背景颜色,如下所示:

List { ... } .introspectTableView { tableView in
                tableView.backgroundColor = .yellow
            }

由于某种原因颜色更改不起作用,您可以尝试将 .listStyle 更改为 .plain

代码:

struct ContentView: View {
var body: some View {
    VStack {
        Text("Test")

        List {
            ForEach(1 ..< 4) { items in
                Text(String(items))
            }
        }
        .listStyle(.plain)
    }
}

iOS 16 提供了一个修改器来自定义 List 背景颜色。

View.scrollContentBackground指定可滚动视图内容的背景样式,包括列表。

List {
    Text("One")
    Text("Two")
}
.scrollContentBackground(Color.red)

您可以通过.hiddenColor.clear隐藏背景 - 如果这样做,列表的背景将可见。

List {
    Text("One")
    Text("Two")
}
.background(Image("MyImage"))
.scrollContentBackground(.hidden)

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

List {
    Section("Header") {
        Text("One")
        Text("Two")
            .listRowBackground(Color.red)
    }
    .listRowBackground(Color.clear)
    .listRowSeparator(.hidden)
}
.scrollContentBackground(.hidden)

在 iOS 16中,我们通过scrollcontentbackground修饰符获得了一种本地方式来执行此操作。

您可以通过将颜色 ( ShapeStyle ) 设置为scrollcontentbackground更改颜色

List {
    Text("Item 1")
    Text("Item 2")
    Text("Item 3")
}
.scrollContentBackground(Color.pink)

或者您可以隐藏背景.scrollContentBackground(.hidden)并使用.backgroud修饰符设置自定义背景。

List {
    Text("Item 1")
    Text("Item 2")
    Text("Item 3")
}
.background {
    Image("ventura")

}
.scrollContentBackground(.hidden)

由于系统背景,更改背景对我不起作用。 我需要隐藏它。

List(examples) { example in
        ExampleRow(example: example)
    }.background(Color.white.edgesIgnoringSafeArea(.all))
        .scrollContentBackground(.hidden)

Xcode 版本 12.4

Background属性对我有用,但强制使用Opacity 没有不透明度是行不通的。

List {
            ForEach(data, id: \.id) { (item) in
                ListRow(item)
                    .environmentObject(self.data)
            }
        }
        .background(Color.black)
        .opacity(0.5)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM