[英]SwiftUI ScrollView image as background error
Thanks for taking your time to help others:)感谢您花时间帮助他人:)
I can apply a color to the ScrollView background, and adjusts perfectly.我可以将颜色应用于 ScrollView 背景,并进行完美调整。
But if I try to set an image as background, the result is not correct, it expands over to the TextField and even safeArea.但是,如果我尝试将图像设置为背景,结果是不正确的,它会扩展到 TextField 甚至 safeArea。
I need this because I'm building a chat.我需要这个,因为我正在聊天。 And I can't use a ZStack to put the image under the ScrollView, it's complex to explain why.
而且我不能使用 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")
}
}
This is the result of Timmy's answer.这是 Timmy 回答的结果。 Almost the thing but it moves when keyboard appears.
几乎是这样,但是当键盘出现时它会移动。
You need to set the background of the TextField
to white (or whatever color you need):您需要将
TextField
的背景设置为白色(或您需要的任何颜色):
TextField("Your text here", text: $text)
.textFieldStyle(.roundedBorder)
.padding()
.background(Color.white)
Update:更新:
In order for the image to bound itself correctly, you need to use the .clipped()
modifier after the background one:为了使图像正确绑定自身,您需要在背景后使用
.clipped()
修饰符:
.background {
Image("chatBackground")
.resizable() //recommended
.aspectRatio(contentMode: .fill) //recommended
}.clipped()
To make the image ignore the keyboard, you need to wrap the image inside a GeometryReader
& add .ignoresSafeArea(.keyboard, edges: .bottom)
(Credit to @pawello2222 ):要使图像忽略键盘,您需要将图像包裹在
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.