我希望狀態欄和底部為白色(與根背景顏色相同),但不知道,我是否需要獲取狀態欄高度并添加頂部和底部邊距?
這是我的代碼和下面的預覽
import SwiftUI
struct ContentView: View {
var body: some View {
VStack(
alignment: .leading,
spacing: 10
) {
Text("Title")
.font(
.system(size: 32)
.weight(.heavy)
)
Text("Content")
}
.frame(
minWidth: 0,
maxWidth: .infinity,
minHeight: 0,
maxHeight: .infinity,
alignment: .topLeading
)
.padding(
EdgeInsets(
top: 0,
leading: 20,
bottom: 0,
trailing: 20
)
)
.background(Color.gray)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
Group {
ContentView()
}
}
}

uj5u.com熱心網友回復:
如果是我處理這種 UI,我會使用 SwiftUI 為我們提供的其他一些不錯的視圖(例如ZStack)。將ZStack物件自下而上置于另一個之上。所以你會首先想要你的顏色,然后是VStack之后。它看起來像這樣:
struct ContentView: View {
var body: some View {
ZStack {
Color.gray
VStack(alignment: .leading, spacing: 10) {
Text("Title")
.font(.system(size: 32).weight(.heavy))
Text("Content")
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.padding()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
uj5u.com熱心網友回復:
添加 1 的垂直填充:
struct ContentView: View {
var body: some View {
VStack(alignment: .leading, spacing: 10) {
Text("Title")
.font(.system(size: 32).weight(.heavy))
Text("Content")
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.padding(.horizontal, 20)
.background(Color.gray)
.padding(.vertical, 1) // here
}
}
uj5u.com熱心網友回復:
讓我添加另一個采用不同方法的答案,而不使用.frame(). HStack相反,它使用 和 的整個寬度和高度VStack來填充螢屏。對于狀態欄和底部區域,這種方法.layoutPriority()對灰色使用了修飾符,但不允許它與安全區域重疊。
雖然其他答案作業得很好,但我在這個例子中的目的是打開可能性的范圍。
struct Example: View {
var body: some View {
HStack {
VStack(alignment: .leading, spacing: 10) {
Text("Title")
.font(
.system(size: 32)
.weight(.heavy)
)
Text("Content")
Spacer() // This spacer will extend the VStack to full height
}
Spacer() // This spacer will extend the HStack to full width
}
.padding()
.background {
VStack {
// Status bar
Color.clear
.ignoresSafeArea()
// Rest of the view: gray has the priority but can't overlap
// the status bar
Color.gray
.layoutPriority(1)
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/468366.html
