iosswiftswiftui

How to keep View stick to the bottom when keyboard appears? ignoresSafeArea(.keyboard) doesnt work


How to keep that bottom label stick to the bottom when keyboard appears?

Here is the code:

struct StartView: View {
    @State private var selection = 1
    var body: some View {
        RoundedTabView(selectedTab: $selection)
    }
}

struct RoundedTabView: View {
    @Binding var selectedTab: Int
    
    var body: some View {
        ZStack(alignment: .bottom) {
            TestView()
            ZStack{
                Text("should be sticked")
            }
        }
    }
}

struct TestView: View {
    @State var text = "hejka john text field"
    var body: some View {
        ZStack {
            Color.orange
                .ignoresSafeArea()
            TextField("", text: $text)
                .multilineTextAlignment(.center)
        }
    }
}

IMPORTANT:

It should stick only that label, not the TextField itself. TextField should move up when keyboard appears and if at that time is under the keyboard.

enter image description here enter image description here


Solution

  • The modifier .ignoresSafeArea(.keyboard) is the correct way to ignore the keyboard. However, it only seems to work when the text is pushed to the bottom in a way that ensures it remains in contact with the safe area.

    One way to do this is to apply a .frame with alignment: .bottom:

    // RoundedTabView
    
    var body: some View {
        ZStack {
            TestView()
            Text("should stick to bottom of screen")
                .frame(maxHeight: .infinity, alignment: .bottom)
                .ignoresSafeArea(.keyboard)
        }
    }
    

    Alternatively, you can use a VStack with Spacer:

    var body: some View {
        ZStack {
            TestView()
            VStack {
                Spacer()
                Text("should stick to bottom of screen")
            }
            .ignoresSafeArea(.keyboard)
        }
    }
    

    Animation