[英]SwiftUI ScrollView image as background error
感謝您花時間幫助他人:)
我可以將顏色應用於 ScrollView 背景,並進行完美調整。
但是,如果我嘗試將圖像設置為背景,結果是不正確的,它會擴展到 TextField 甚至 safeArea。
我需要這個,因為我正在聊天。 而且我不能使用 ZStack將圖像放在 ScrollView 下,解釋原因很復雜。
import SwiftUI
struct ContentView: View {
@State var text: String = ""
var body: some View {
VStack {
ScrollView() {
LazyVStack {
HStack {
Spacer()
}
ForEach(1..<201, id: \.self) { num in
Text("Message \(num)")
}
}
}
// .background(Color.red) // Good result, adjusted where I want to
.background(Image("chatBackground")) // Bad result, expands to TextField and safe area
TextField("Your text here", text: $text)
.textFieldStyle(.roundedBorder)
.padding()
}
.navigationBarTitleDisplayMode(.inline)
.navigationTitle("Example app")
}
}
您需要將TextField
的背景設置為白色(或您需要的任何顏色):
TextField("Your text here", text: $text)
.textFieldStyle(.roundedBorder)
.padding()
.background(Color.white)
更新:
為了使圖像正確綁定自身,您需要在背景后使用.clipped()
修飾符:
.background {
Image("chatBackground")
.resizable() //recommended
.aspectRatio(contentMode: .fill) //recommended
}.clipped()
要使圖像忽略鍵盤,您需要將圖像包裹在GeometryReader
中並添加.ignoresSafeArea(.keyboard, edges: .bottom)
(感謝 @pawello2222 ):
.background {
GeometryReader { _ in
Image("chatBackground")
.resizable()
.aspectRatio(contentMode: .fill)
}.ignoresSafeArea(.keyboard, edges: .bottom)
}.clipped()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.