SwiftUI ScrollView图像作为背景错误

whhtz7ly  于 2023-02-03  发布在  Swift
关注(0)|答案(1)|浏览(108)

谢谢你花时间帮助别人:)

漏洞描述:

我可以应用一个颜色到滚动视图背景,并调整完美。
但如果我尝试将图像设置为背景,结果是不正确的,它会扩展到TextField甚至safeArea。
我需要这个,因为我正在建立一个聊天。和我不能使用ZStack把图像下的滚动视图,这是复杂的解释。

测试它的简单代码。

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")
    }
}

结果:

1.良好结果(使用颜色):

1.不良结果(使用图像):

问题

1.如何将图像用作背景?
1.为什么它会一直延伸到最底部?

编辑

这是Timmy的回答的结果。几乎是东西,但它移动时,键盘出现。

iszxjhcz

iszxjhcz1#

您需要将TextField的背景设置为白色(或您需要的任何颜色):

TextField("Your text here", text: $text)       
    .textFieldStyle(.roundedBorder)
    .padding()
    .background(Color.white)
    • 更新日期:**

为了使图像正确绑定自身,需要在背景修饰符之后使用.clipped()修饰符:

.background {
    Image("chatBackground")
        .resizable() //recommended
        .aspectRatio(contentMode: .fill) //recommended
}.clipped()

要使图像忽略键盘,需要将图像 Package 在GeometryReader中并添加.ignoresSafeArea(.keyboard, edges: .bottom)(归功于@pawelllo2222):

.background {
    GeometryReader { _ in
        Image("chatBackground")
            .resizable()
            .aspectRatio(contentMode: .fill)
    }.ignoresSafeArea(.keyboard, edges: .bottom)
}.clipped()

相关问题