Home > Back-end >  Navigation bar title is stuck
Navigation bar title is stuck

Time:07-13

If I use a toolbar for the keyboard which has a ScrollView inside it messes up the navigation bar title which will just be positioned stuck at the screen instead of moving in the navigation bar.

Does anyone have a solution for this issue?

(Xcode 13.4.1)

Minimal reproducible code:

struct MyApp: App {
        
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

struct ContentView: View {
    
    @State var numbers = Array(1...100).map { String($0) }
    
    var body: some View {
        NavigationView {
            List($numbers, id: \.self) { $number in
                TextField("", text: $number)
            }
            .toolbar {
                ToolbarItem(placement: .keyboard) {
                    ScrollView(.horizontal) {
                        HStack {
                            Text("Hello")
                            Text("World")
                        }
                    }
                }
            }
            .navigationTitle("Messed up title")
        }
    }
}

Messed up title

CodePudding user response:

I copied/pasted and ran your code. The result was different from your provided image. I'm using Xcode 14, iOS 16.

enter image description here

CodePudding user response:

It seems like you are trying to add 100 toolbar item elements inside your keyboard which is causing performance issue and impacting on your navigation bar. if you want to show 100 toolbar item elements then instead of adding inside keyboard add separate View and add on top of it and then based on keyboard appear or disappear hide/show 100 elements view accordingly. So I modify your code which is adding two toolbar items elements inside your keyboard and that seems to be working fine without any navigation title stuck issue eg below:-

var body: some View {
        NavigationView {
            List($numbers, id: \.self) { $number in
                TextField("", text: $number)
            }.toolbar {
                ToolbarItem(placement: .keyboard) {
                    HStack {
                        Button("Cancel") {
                            print("Pressed")
                        }
                        Spacer()
                        Button("Done") {
                            print("Pressed")
                        }
                    }
                }
            }.navigationTitle("Messed up title")
        }
    }
  • Related