10

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

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)我得到的最好的就是这个

问题

4

1 回答 1

37

iOS 14

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

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

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


iOS 13

所有 SwiftUIList都由UITableViewiOS 中的 a 支持。所以你需要改变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

于 2019-10-28T13:44:00.087 回答