skip to Main Content

When I click my SwiftUI text field and the keyboard opens, the app zooms out (shown in video).

I have two questions about this behaviour:

  1. Why does this happen?
  2. How do I avoid this happening?

Here is my code:

struct BestillView: View { // This view is put inside a tab view with .ignoresSafeArea
    @State var navn = ""
    @State var varsling = true
    
    var body: some View {
        NavigationView {

            ZStack {

                Color("BackgroundColor")
                    .ignoresSafeArea()
                VStack {
                    Image("Liquid") // This is my image overlayed on the background, i suspect this may be the only element that actually gets zoomed out
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .ignoresSafeArea()
                    Spacer()
                }
                

                VStack {
                    ZStack(alignment: .leading) { // This is where the text field i'm having trouble with is
                        Color("UnselectedColor")
                            .frame(height: 50)
                            .cornerRadius(20.0)
                        if navn.isEmpty { // I have a separate text element as the placeholder text so i can give it a custom color
                            Text("Navn")
                                .foregroundColor(Color("AccentColor"))
                                .padding()
                        }
                        TextField("", text: $navn)
                            .padding()
                    }
                    .frame(width: 300)
                    


                    Spacer()
                        .frame(height: 20.0)
                    
                    // I removed the rest of my code, I don't think it should be necessary in this question - it's only a NavigationLink and a Toggle
                }
            }
        }
    }
}

2

Answers


  1. You have .ignoresSafeArea() on your Image, but you actually need it on the VStack that contains the Image. The VStack is shrinking to fit the keyboard’s safe area, which squeezes the image too.

    Login or Signup to reply.
  2. The view is actually not shrinking; the image is shrinking – because as the view moves up, it has less height to fit.

    You can update your code as:

    Image("Liquid")
        .aspectRatio(contentMode: .fill)
    

    and it will keep the size same – as the width will remain same.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search