【问题标题】:How to set the background color of a List in a NavigationView如何在 NavigationView 中设置列​​表的背景颜色
【发布时间】:2021-08-04 08:29:45
【问题描述】:

考虑一个包含List 项的NavigationView。如何给这个背景颜色?

  • NavigationView 放入ZStack - 不起作用
  • ZStack 放入NavigationView(下面的代码示例) - 不起作用
struct test: View {
    var body: some View {
        NavigationView {
            ZStack {
                Color.blue
                List {
                    ForEach(["1", "2", "3"], id: \.self) { item in
                        NavigationLink(destination: EmptyView()) {
                            Text("Some title")
                        }
                    }
                }
                .navigationTitle("Items")
            }
        }
    }
}

【问题讨论】:

标签: ios swiftui swiftui-list swiftui-navigationview


【解决方案1】:
  • 将 ZStack 放在 NavigationView 中,同时设置 List 的 UITableView onAppear 的外观。
  • 在 ForEach 上设置 .listRowBackground 以使单元格获得相同的背景颜色。
struct test: View {
    var body: some View {
        NavigationView {
            ZStack {
                Color.blue.edgesIgnoringSafeArea(.all)
                List {
                    ForEach(["1", "2", "3"], id: \.self) { item in
                        NavigationLink(destination: EmptyView()) {
                            Text("Some title")
                        }
                    }.listRowBackground(Color.blue)
                }
                .onAppear() {
                    UITableView.appearance().backgroundColor = UIColor.clear
                    UITableViewCell.appearance().backgroundColor = UIColor.clear
                }
                .navigationTitle("Items")
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    如果您不想更改应用中每个ListForm 的外观,可以使用SwiftUI-Introspect

    我在 SwiftUI 中更改了列表行的背景颜色,并使用 Introspect 设置了背景,因此它影响这个 List 而没有其他影响。

    代码:

    NavigationView {
        List {
            ForEach(["1", "2", "3"], id: \.self) { item in
                NavigationLink(destination: EmptyView()) {
                    Text("Some title")
                }
                .listRowBackground(Color.blue)
            }
        }
        .introspectTableView { tableView in
            tableView.backgroundColor = .systemBlue
        }
        .navigationTitle("Items")
    }
    

    注意:UIKit 的 .systemBlue 等价于 SwiftUI 的 .blue

    【讨论】:

      猜你喜欢
      • 2019-12-21
      • 2020-02-19
      • 1970-01-01
      • 1970-01-01
      • 2011-05-29
      • 2020-01-01
      • 2011-11-18
      • 1970-01-01
      • 2010-12-11
      相关资源
      最近更新 更多