Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在SwiftUI中修改列表的背景色?_Swift_Swiftui - Fatal编程技术网

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

如何在SwiftUI中修改列表的背景色?,swift,swiftui,Swift,Swiftui,我试图在SwiftUI中重新创建一个用UIKit构建的UI,但遇到了一些小问题 我想在这里更改列表的颜色,但是没有任何属性像我期望的那样工作。示例代码如下: struct ListView: View { @EnvironmentObject var listData: ListData var body: some View { NavigationView { List(listData.items) { item in

我试图在SwiftUI中重新创建一个用UIKit构建的UI,但遇到了一些小问题

我想在这里更改
列表的颜色,但是没有任何属性像我期望的那样工作。示例代码如下:

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

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

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

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

struct TestRow: View {

    var body: some View {
        Text("This is a row!")
        .listRowBackground(Color.green)
    }
}
然后在身体里:

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

这与我预期的一样有效,但我还没有找到如何删除行之间的分隔线…

如果试图使用
.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"))
    }
}
我假设修改器应该这样做,但从Xcode 11 Beta 11M336w起就不是这样了

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

我不知道连接是什么,但是如果你用
表单
包装列表,它就工作了

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

您可以通过更改
UITableView
的外观来完成此操作

UITableView.appearance().backgroundColor = UIColor.clear
只需将这一行放入
Appdelegate
didfishlaunchingwithoptions
方法。 替换
UIColor。清除
设置要添加到
列表的背景色中的任何颜色


我启发了一些用于配置每页导航视图导航栏样式的配置程序,并编写了一些简单的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)
            }
        }
    }

也许有一件事需要改进,那就是使用navigationController?.topViewController使其即使在视图控制器层次结构中没有navigationController也能工作对我来说,在SwiftUI中更改列表背景的完美解决方案是:

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

}

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

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

这个名单还不完善

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

在我这方面,这是迄今为止效果最好的。 正如@FontFamily所说,它不应该破坏任何
列表
默认行为,如刷卡。

.colorMultiply(…) 对于列表背景,请使用
.colorMultiply(Color.yourColor)
修饰符

示例:

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

     Text(element)

}
.colorMultiply(Color.red) <--------- replace with your color
List(元素,id:\.self){中的元素
文本(元素)
}

.colorMultiply(Color.red)在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())
    }

基本上,如果使用ForEach内部列表,listRowBackground()可以工作。

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

.listRowBackground(Color("backgroundColour").edgesIgnoringSafeArea(.all))
Xcode版本12.4

Background属性对我有效,但必须使用不透明性。 如果没有不透明度则无法工作

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

更改背景色

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

但是,如果需要不同的背景色,可以将默认值设置为清除,并在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现在是令人难以置信的错误,当我使用这样的代码和硬代码我的列表项时,这是可行的。当我异步加载数据时,它不再工作了。是的,这有点痛苦。不过玩起来很有趣。应该会很快变得更平稳,hopefully@MariusWaldal你找到如何更改分区视图背景颜色了吗?@andromedainiative Do List{ForEach(items,id:\.self){item in Text(item).listRowBackground(color.green)}取而代之的是,它可以工作了。我遇到了一个非常愚蠢的问题,.listRowBackground()修饰符必须在.contextMenu()修饰符之后,否则它将不起作用。Xcode 12.0.1Hi@caleb81389,它对我起作用,但它不会应用于空行。你知道为什么吗?不,对不起。我不知道如何将其应用于空行。也许你可以人为地放置空白文本““在标签或其他东西中…?除了SwiftUI有点做它想做的事情,类似的事情需要比我还多的人来回答。如果你弄明白了,请告诉我!正如Caleb指出的那样,listRowBackground不应该应用于列表,而应该应用于行项目本身。此外,你应该能够只使用颜色(“Primary”)不是强制展开UIColor:)这是可行的,但是,我在列表中有一个节标题,该标题现在不是
粘性的
——它随列表移动:(.它是有效的,但我仍在思考如何改变列表本身的背景。这是唯一对我也有效的方法。我认为重要的是要强调,你必须拥有
List{ForEach(elements){}
,而不是
List(elements){}
以使此修改器正常工作。您指定列表数据的方式使此修改器无法正常工作,这太荒唐了。看到SwiftUI中的此类错误,不会在整个SwiftUI上留下良好的视图。它可以正常工作,但不会删除实际显示的行下的白色背景编辑执行任务:UITableViewCell.appearance().backgroundColor=.Clear是否有针对Mac的解决方案?我将如何在不同的列表中改变它?我将此应用于一个选项卡中的一个列表,这会影响另一个选项卡视图中的另一个列表。很好,也可以使用:UITableView。
List {
            ForEach(data, id: \.id) { (item) in
                ListRow(item)
                    .environmentObject(self.data)
            }
        }
        .background(Color.black)
        .opacity(0.5)
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
            }
        )
    }
}
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
}
// 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()
        }
    }
}