簡體   English   中英

SwiftUI ScrollView 圖片作為背景錯誤

[英]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")
    }
}

結果:

  1. 好的結果(使用顏色): 好的結果(使用顏色)

  2. 錯誤的結果(使用圖像): 結果不好(使用圖像)

問題

  1. 如何應用圖像作為背景?
  2. 為什么會延伸到最底層?

編輯

這是 Timmy 回答的結果。 幾乎是這樣,但是當鍵盤出現時它會移動。 在此處輸入圖像描述

您需要將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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM