[英]Screen Background Color With ScrollView And Navigation Bar SwiftUI
我在使用带有 SwiftUI 的滚动视图时尝试使用彩色背景,但这会导致导航标题不再折叠。 我尝试了多种方法,但这始终是一个问题。
struct Person : Identifiable{
var id : Int
var name : String
}
struct ContentView: View {
let people = [
Person(id: 1, name: "Ricky"),
Person(id: 2, name: "Dani"),
Person(id: 3, name: "Mark"),
Person(id: 4, name: "Kailin"),
Person(id: 5, name: "James"),
Person(id: 5, name: "Jenna")
]
var body: some View {
NavigationView{
ZStack{
Color.red
.edgesIgnoringSafeArea(.all)
ScrollView{
ForEach(people, id: \.id) { person in
Text(person.name)
.frame(width: 300, height: 400)
.background(Color.blue)
.padding()
}
}.navigationBarTitle("Home")
}
}
}
// init(){
// UIView.appearance().backgroundColor = .orange
// }
}
像这样重新排列您的视图:
var body: some View {
NavigationView {
ScrollView {
ZStack {
Color.red
VStack {
ForEach(people, id: \.id) { person in
Text(person.name)
.frame(width: 300, height: 400)
.background(Color.blue)
.padding()
}
}
}
}.navigationBarTitle("Home")
}
您可以使用以下修饰符本地更改导航栏的颜色:
.toolbarBackground(.yellow, in: .navigationBar)
这仅适用于内联导航栏(具有无缝动画)
您可以使用UINavigationBar.appearance().backgroundColor = .red
和另一个UIColor
(如Color(UIColor.red)
作为背景)来模拟透明的大型NavigationBar
,直到用于在 SwiftUI 中更改正确颜色的直接 API 到来。
注意 1: UIColor.red
与Color.red
略有不同。
注意 2:如果您想使用List
而不是ScrollView
,您应该将.listRowInsets(EdgeInsets())
添加到ZStack
以消除额外的空白。
这是我想出的解决方案...此解决方案还允许您将背景单元格着色为与列表元素不同的颜色。 你可以用 ScrollView 做一个非常相似的事情
正如其他解决方案的评论中所述,使用 ListView 执行该解决方案会从单元格中留下一堆空白。 (这就是为什么这很有用)
我想我会补充一点,因为其他解决方案都不适合我。
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))
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.