简体   繁体   中英

SwiftUI: How to set background color for textfield

描述

When I select the textfield, it gets rid of its background color where the text is supposed to be. I attached an image showing the Card holder textfield for example. Maybe it's just a bug? Here is my code for the "CardHolderView":

Reproducing the error:

struct ContentView: View {
    init() {
        UINavigationBar.appearance().barTintColor = #colorLiteral(red: 0.9384715557, green: 0.9561783671, blue: 1, alpha: 1)
        UINavigationBar.appearance().shadowImage = UIImage()
        UIScrollView.appearance().backgroundColor = #colorLiteral(red: 0.9384715557, green: 0.9561783671, blue: 1, alpha: 1)
    }
    
    @State private var name = ""
    
    var body: some View {
        NavigationView {
            ScrollView(UIScreen.main.bounds.height < 750 ? .vertical : .init()) {
                ZStack {
                    Color(#colorLiteral(red: 0.9384715557, green: 0.9561783671, blue: 1, alpha: 1)).edgesIgnoringSafeArea(.all)
                    CardHolderView(name: $name)
                        .padding()
                }
                .padding(.top, 60)
                .navigationBarTitle("Payment data", displayMode: .inline)
                .navigationBarItems(leading: Button(action: {}) { Image("left-arrow") })
            }
            .edgesIgnoringSafeArea(.all)
        }
    }
}

struct CardHolderView: View {
    @Binding var name: String
    
    var body: some View {
        VStack(alignment: .leading) {
            Text("Card holder")
            TextField("Your name and surname", text: $name)
                .padding()
                .background(Color.white)
                .cornerRadius(10)
        }
        .padding(.top)
    }
}

There is no need to use UIAppearance to set the background color of the ScrollView ; You can use use .background modifier on it.

UIAppearance makes global changes and can have unintended consequences.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM