![](/img/trans.png)
[英]How can I make a SwiftUI List row background color extend the full width, including outside of the safe area
[英]How can I use edgesIgnoringSafeArea in SwiftUI, but make a child view respect the safe area?
我正在構建一個帶有列表視圖的 UI 是 SwiftUI,我想在列表視圖的一部分上放置一個面板,上面有一個按鈕。
在底部有安全區域(沒有物理主頁按鈕)的設備上,我希望面板位於屏幕底部的 go。 但我想確保面板上的按鈕不會延伸到安全區域。
在我的示例代碼中, HStack
是包含按鈕的面板。 我嘗試向其中添加.edgesIgnoringSafeArea(.bottom)
,但這不允許它延伸到底部。 這讓我有點困惑,因為同一個ZStack
中的列表延伸到底部安全區域。
當我將.edgesIgnoringSafeArea(.bottom)
添加到ZStack
時,允許HStack
(藍色面板)延伸到屏幕底部的安全區域。 這就是我想要的,但是一旦我這樣做了,我怎么能告訴作為HStack
子項的Button
不要忽略安全區域?
我知道如何在 UIKit 中執行此操作,但我真的希望能夠在 SwiftUI 中構建此 UI。我可以手動添加一些填充或 Spacers 以在Button
下添加額外的填充以說明安全區域,但隨后帶有主頁按鈕但沒有底部安全區域的設備會有額外的間距。 我想找出一個優雅的解決方案,我可以依靠系統來定義其安全區域,而不是手動定義任何數字間距或為不同設備創建條件情況。
struct ContentView: View {
var body: some View {
ZStack(alignment: .bottom) {
List {
Text("Item 1")
Text("Item 2")
Text("Item 3")
}
HStack {
Spacer()
Button(action: {
// do something
}){
Text("Button")
.font(.title)
.padding()
.background(Color.green)
.foregroundColor(.white)
.cornerRadius(15)
}.padding()
Spacer()
}.background(Color.blue).edgesIgnoringSafeArea(.bottom)
}
}
}
您在背景修改器中繪制的任何視圖都將使用它正在修改的視圖的框架。 所以你需要告訴那個視圖忽略安全區域。
.background(Color.blue.edgesIgnoringSafeArea(.bottom))
您可以使用 GeometryReader 訪問安全區域的高度。 然后您可以使用安全區域的高度作為按鈕的底部填充或偏移。
https://developer.apple.com/documentation/swiftui/geometryproxy
struct ContentView: View {
var body: some View {
GeometryReader { proxy in
ZStack(alignment: .bottom) {
List {
Text("Item 1")
Text("Item 2")
Text("Item 3")
}
HStack {
Spacer()
Button(action: {
// do something
}){
Text("Button")
.font(.title)
.padding()
.background(Color.green)
.foregroundColor(.white)
.cornerRadius(15)
}
.padding(.bottom, proxy.safeAreaInsets.top)
Spacer()
}.background(Color.blue)
}.edgesIgnoringSafeArea(.bottom)
}
}
}
添加到@Joe Susnick 的回答中,完整的代碼是:
VStack {
}.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color(red: 0.357, green: 0.784, blue: 0.016, opacity: 0.5).ignoresSafeArea()
)
VStack 內部的任何內容都尊重安全區域,而背景會填滿整個屏幕。
edgeIgnoringSafeArea(_:) 已棄用
使用以下內容:
.background(Color.blue.ignoresSafeArea(edges: .bottom))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.