I came across an issue when building a SwiftUI cross platform app recently. I did not want a large navigationBarTitle on iOS, I wanted it in the toolbar, but if I set displayMode to inline the watchOS version will not compile as it is not supported there. Basically the following code won’t work on watchOS.
NavigationView {
.navigationBarTitle("Title", displayMode: .inline)
}
I did not want to have to have a lot of platform specific code so a workaround I found is to declare navigationBarTitle without the displayMode set to inline and then add iOS #if code to add to the toolbar, then extend the View object and navigationBarTitle on iOS which will hide navigationBarTitle and hide the padding it creates at the top. Like below.
#if os(iOS)
extension View {
func navigationBarTitle(_ title: String) -> some View {
self.navigationBarTitleDisplayMode(.inline)
}
}
#endif
// Then you can just do this anywhere for iOS and watchOS.
.navigationBarTitle("Title")
//and then in your view, to show a title in the toolbar for iOS
#if os(iOS)
ToolbarItem(placement: .principal) {
Text("Title")
}
#endif
2 replies on “navigationBarTitle Display Inline when sharing code between iOS and watchOS”
Hi, thanks for the tip. I am trying to do the opposite so it applies to a watchOS app:
@available(watchOSApplicationExtension 8.0, *)
extension View {
func navigationBarTitle(_ title: String) -> some View {
self.navigationBarTitleDisplayMode(.inline)
}
}
But it doesn’t seem to do anything, do you know if I’m missing anything? Thanks.
Hi Alan,
Sorry I missed your comment previously, did you mange to get this working for yourself?