Categories
Uncategorized

navigationBarTitle Display Inline when sharing code between iOS and watchOS

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 

Leave a Reply

Your email address will not be published. Required fields are marked *