如何在SwiftUI中设置NavigationView的背景颜色

4

我试图设置一个NavigationView的背景颜色。我尝试使用下面的代码添加ZStack(部分来自SwiftUI教程)。然而,除非我将NavigationView...替换为Spacer(),否则它始终是白色。

    var body: some View {
    ZStack
        {
            NavigationView {
                List {
                    Toggle(isOn: $userData.showFavoritesOnly) {
                        Text("Favourites")
                    }
                    ForEach(userData.landmarks) { landmark in
                        if !self.userData.showFavoritesOnly || landmark.isFavorite {
                            NavigationLink(destination: LandmarkDetail(landmark: landmark)) {
                                LandmarkRow(landmark: landmark)
                            }
                        }
                    }
                }

                .navigationBarTitle(Text("Landmarks"), displayMode: .large)
            }

    }.background(Color.blue.edgesIgnoringSafeArea(.all))
}

我可以设置每个列表项的颜色,但我想让整个背景显示蓝色。


不允许编辑问题并将其更改为完全不同的问题。请将其改回原始问题并提出另一个问题。 - Mojtaba Hosseini
同一个问题。澄清我正在尝试更改背景的方式。 - Wayneio
看看由于不同的“澄清”而得出的答案有何不同?希望对你有所帮助。 - Mojtaba Hosseini
1
我看到我对问题的澄清帮助你理解了 :) - Wayneio
请查看我的示例这里 - Victor Kushnerov
3个回答

15

它与UINavigationBar相同。但由于目前尚无直接的API,您可以使用appearance进行更改:

UINavigationBar.appearance().backgroundColor = .orange
UINavigationBar.appearance().tintColor = .green
UINavigationBar.appearance().barTintColor = .yellow
UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: UIColor.red]
UINavigationBar.appearance().largeTitleTextAttributes = [.foregroundColor: UIColor.red]

你应该将这个放在编译器可以读取的地方,例如init()方法内。

请注意,其中一些将不适用于Xcode 11 beta 5以下版本。


1
谢谢,这很有帮助,几乎就是我需要的。我将UINavigationBar换成了UIView,所有的背景都改变了。 - Wayneio
2
切换到UIView会更改背景,但SwiftUI内容不显示。你找到让它出现的方法了吗? - Richard Witherspoon
也许如果您发布一个包含可重现问题的最小工作代码,我可以找到解决方法;@RichardWitherspoon。在此处发布一个问题并评论其链接以通知我,我一定会尽力帮助您。 - Mojtaba Hosseini
@MojtabaHosseini 这是我试图通过查看这个问题来解决的问题链接 https://dev59.com/RlMH5IYBdhLWcg3w3Ejb - Richard Witherspoon

3

这似乎是使导航视图透明的关键:UITableView.appearance().backgroundColor = .clear

感谢https://izziswift.com/swiftui-list-color-background/提供此代码片段。

以下是我使用Xcode 13 Beta针对iOS 15 Beta编写并测试的代码:屏幕截图...也在部署到iPhone 12 iOS 14.7的Xcode 13 Beta上测试过。

它也可以与Xcode 12.x和iOS 14.x一起使用(请查看有关可潜在删除的SwiftUI 3功能的评论等)。

//  NavigationView.swift
//  swiftui.proto2
//
//  Created by Sunil Raman on 12/8/21
//  Updated by Sunil Raman on 18/8/21

import SwiftUI

//Testing gradient backgrounds, etc. (may require Xcode 13)
//Credit: https://sarunw.com/posts/how-to-set-screen-background-color-in-swiftui/
let backgroundGradient = LinearGradient(
    colors: [Color.purple, Color.red],
    startPoint: .top, endPoint: .bottom)

//Build view here!
struct MyCoolListView: View {
    
    //The "magic" happens here
    //Credit: https://izziswift.com/swiftui-list-color-background/
    init() {
        //Appears to be the key to making Navigation View transparent
        UITableView.appearance().backgroundColor = .clear
        //Just for reference, not sure if opacity can be adjusted
        UINavigationBar.appearance().barTintColor = .white
    }
        
    //Our view, of course
    var body: some View {
      
        //Our navigation view
        NavigationView {
            
            //Our list
            List() {
            
                //Testing sections w.r.t. layout purposes, formatting section headers, etc.
                Section(header: Text("Section 1").font(.title2).foregroundColor(.yellow)) {
                    NavigationLink("Text 1", destination: MyCoolListView())
                    NavigationLink("Text 1", destination: MyCoolListView())
                    NavigationLink("Text 1", destination: MyCoolListView())
                }
                
                Section(header: Text("Section 2").font(.title3).fontWeight(.bold)) {
                    NavigationLink("Text 2", destination: MyCoolListView())
                    NavigationLink("Text 2", destination: MyCoolListView())
                    NavigationLink("Text 2", destination: MyCoolListView())
                }
                        
                Section(header: Text("Section 3").font(.title3).fontWeight(.light)) {
                    NavigationLink("Text 3", destination: MyCoolListView())
                    NavigationLink("Text 3", destination: MyCoolListView())
                    NavigationLink("Text 3", destination: MyCoolListView())
                }
                        
                //For reference, you can uncomment this to test
                //.listRowBackground(Color.blue)
                        
           }
           .listStyle(.insetGrouped)
           //This simulates a "material" type effect, hard to apply to Lists even in SwiftUI 3?
           .opacity(0.65)
           //New SwiftUI 3 feature, you can use if #available(iOS 15, *) or something
           //.refreshable {
               //Refresh action here
           //}
           //Can the navigation title be manipulated further? Not sure.
           .navigationTitle(Text("Title"))
           //The awesome background!
           .background(backgroundGradient)
           //This helps with iOS 14.7 
           .ignoresSafeArea()
                                
        } //End NavigationView
        
    } //End some View
    
} //End struct


//Enabling the previewing in Xcode
struct MyCoolListView_Previews: PreviewProvider {
    static var previews: some View {
        if #available(iOS 15.0, *) {
            MyCoolListView()
                .previewInterfaceOrientation(.landscapeLeft)
        } else {
            // Fallback on earlier versions
        }
    }
}

-1

这是我想出来的解决方案... 这个解决方案还允许你将背景单元格的颜色与列表元素的颜色区分开来。

由于 ZStack 不起作用,而 UIView/UINavigationBar.appearance().backgroundColor 会改变整个可见屏幕的颜色,所以我想补充一下。

我觉得我应该补充一下,因为其他的解决方案对我都不起作用。

struct ListBackgroundColor: ViewModifier {

    let color: UIColor

    func body(content: Content) -> some View {
        content
            .onAppear() {
                UITableView.appearance().backgroundColor = self.color
                //(Optional) Edit colour of cell background
                UITableViewCell.appearance().backgroundColor = self.color
            }
    }
}   

extension View {
    func listBackgroundColor(color: UIColor) -> some View {
        ModifiedContent(content: self, modifier: ListBackgroundColor(color: color))
    }

}

enter image description here


1
你的解决方案没有解决问题,问题特别涉及 NavigationView 而不是任何 View。 - LukeSideWalker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接