Home > Software engineering >  Navigation Title is not showing on SwiftUI
Navigation Title is not showing on SwiftUI

Time:02-14

The navigationTitle is not working. I use Swift5.5.2 In the preview there is no sign of the navigation title just an empty space.


struct ContentView: View {
    
    @State private var firstname = ""
    @State private var lastname = ""
    @State private var birthdate = Date()
    @State private var shouldSendNewsletter = false
    
    
    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("Personal Information")) {
                    TextField("First Name", text: $firstname)
                    TextField("Last Name", text: $lastname)
                    DatePicker("Birth Date", selection: $birthdate, displayedComponents: .date)
                    
                    Section(header: Text("Actions")) {
                        Toggle("Send Newsletter", isOn: $shouldSendNewsletter)
                    }//:Actions
                    
                }
            }//:Form
        }//: NAVIGATION VIEW
        .navigationTitle("ABC")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Preview of navigation title

CodePudding user response:

.navigationTitle("ABC") should be attached to the topmost view inside your NavigationView:

NavigationView {
    Form {
        Section(header: Text("Personal Information")) {
            TextField("First Name", text: $firstname)
            TextField("Last Name", text: $lastname)
            DatePicker("Birth Date", selection: $birthdate, displayedComponents: .date)

            Section(header: Text("Actions")) {
                Toggle("Send Newsletter", isOn: $shouldSendNewsletter)
            } //: Actions
        }
    } //: Form
    .navigationTitle("ABC") /// <- here!
} //: NAVIGATION VIEW

CodePudding user response:

NavigationView is a container that hold ChildViews inside it. So .navigationTitle resides inside NavigationView, so in order to change navigationTitle we must call it from inside of NavigationView like this

NavigationView{
    VStack{
    }
    .navigationTitle("ABC")
}
  • Related