简体   繁体   中英

Updating SwiftUI navigation bar title

I have a Form view that sets the navigation bar title to "Settings" and a Picker view inside the Form view that sets the navigation bar title to "Options".

When navigating to Picker view, the navigation bar title does not get set to "Options", but the back button text does. Also, when navigating back to Form view, the navigation bar title is changed to "Options".

How can I have the navigation bar title be "Settings" while on Form view and "Options" while on Picker view? Thanks!

var body: some View {
    NavigationView {
        Form {
            Picker(selection: $currentSelection, label: Text("Options")) {
                ForEach(0 ..< options.count) {
                    Text(options[$0])
                }
            }
            .navigationBarTitle("Options", displayMode: .inline)
        }
        .navigationBarTitle("Settings", displayMode: .inline)
    }
}

在此处输入图像描述

Put navigation title modifier inside Picker . Also as same Text view from Picker item is used to present selection in Form we need to make Options title conditional.

Here is a demo of approach. Tested with Xcode 12.4 / iOS 14.4

演示

Form {
    Picker(selection: $currentSelection, label: Text("Options")) {
        ForEach(0 ..< options.count) {
            if $0 != currentSelection {
               Text(options[$0])
                .navigationBarTitle("Options", displayMode: .inline)
            } else {
               Text(options[$0])
            }
        }
    }
}
.navigationBarTitle("Settings", displayMode: .inline)

backup

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