【问题标题】:SwiftUI List Background color [duplicate]SwiftUI 列表背景颜色 [重复]
【发布时间】:2019-10-28 13:31:00
【问题描述】:

我正在尝试使用以下代码将视图背景颜色设置为黑色

struct RuleList: View {[![enter image description here][1]][1]
private var presenter: ConfigurationPresenter?

@ObservedObject
private var viewModel: RowListViewModel

init(presenter: ConfigurationPresenter?, viewModel: RowListViewModel) {
    self.presenter = presenter
    self.viewModel = viewModel
}

var body: some View {
    List(viewModel.configurations) { configuration in
        RuleListRow(website: configuration.website).background(Color.black)
    }.background(Color.black)
}
}

struct RuleListRow: View {
var website: Website
@State private var websiteState = 0

var body: some View {
    VStack {
        Text(website.id).foregroundColor(.white)

        Picker(website.id, selection: $websiteState) {
            Text("Permis").tag(0)
            Text("Ascuns").tag(1)
            Text("Blocat").tag(2)
        }.pickerStyle(SegmentedPickerStyle()).background(Color.crimson)
    }.listRowBackground(Color.green)
}
}

视图托管在一个混合的 UIKit - SwiftUI 故事板中,因此这个特定的视图嵌入在一个 Hosting 控制器中

class ConfigurationHostingController: UIHostingController<RuleList> {
private var presenter: ConfigurationPresenter = ConfigurationPresenter()

required init?(coder: NSCoder) {
    super.init(rootView: RuleList(presenter: presenter, viewModel: presenter.rowListViewModel))
}
}

我试过.background.listRowBackground(Color.black).colorMultiply(.black)我能想到的任何组合,我得到的最好的就是这个

【问题讨论】:

  • 您是否尝试过更改堆栈本身的背景颜色?

标签: swiftui ios13 xcode11 swiftui-list


【解决方案1】:

iOS 14

在 iOS 14 中,您可以考虑使用 LazyVStack 而不是列表:

ScrollView {
    LazyVStack {
        ForEach((1...100), id: \.self) {
            Text("Placeholder \($0)")
        }
    }
    .background(Color.yellow)
}

请记住,LazyVStack 是惰性的,不会一直呈现所有行。因此,它们的性能非常好,Apple 自己在 WWDC 2020 上提出了建议。


iOS 13

所有 SwiftUI 的 Lists 都由 iOS 中的 UITableView支持。所以你需要改变tableView的背景颜色。但由于ColorUIColor 的值略有不同,可以去掉UIColor

struct ContentView: View {
    
    init() {
        /// These could be anywhere before the list has loaded.
        UITableView.appearance().backgroundColor = .clear // tableview background
        UITableViewCell.appearance().backgroundColor = .clear // cell background
    }

    var body: some View {
        List {
            ,,,
        }
        .background(Color.yellow)
    }
}

现在您可以使用您想要的任何背景(包括所有Colors)

请注意那些顶部和底部的白色区域是安全的,您可以使用.edgesIgnoringSafeArea() 修饰符来消除它们。

⚠️重要提示!

Apple 正在弃用我们在 SwiftUI 中使用的所有 UIKit 技巧(例如调整 UIAppearance)。所以你可能需要考虑让你的代码始终适应最新的 iOS

【讨论】:

  • 就是这样。我试过只为表格设置它,但显然单元格也需要它。
  • 我注意到这也会改变任何后续视图的颜色。例如,从我的列表中,我打开一张纸,颜色都变了。有没有办法让这个工作适用于单个视图或在其他视图上重置?
  • 是的,使用 onAppear 修饰符而不是 init
  • @MojtabaHosseini 将它放在onAppear 上会导致我的其他表仍然具有清晰的行为。我还能做什么?
  • 使用这种方法的单元格内容视图仍然是黑色的。所以你需要像'UIView.appearance().backgroundColor = .white'这样的东西哈哈
猜你喜欢
  • 2019-11-29
  • 1970-01-01
  • 2021-09-22
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
  • 1970-01-01
  • 2012-10-20
相关资源
最近更新 更多