Swiftui: Navigation Bar Title in Reusable Cross-Platform (iOS & MACos) View

SwiftUI: Navigation Bar Title in Reusable Cross-Platform (iOS & macOS) View

I established one approach: Move the main content to another View property, then modify it to add the navbar title (if needed) before returning it as body. When it's separated this way, conditional compilation can be used.

It's a bit inelegant, but it works. It can also be used to set macOS-specific things, such as the view's overall frame size. Suggestions on a better approach are welcome!

Swift v5.1

public struct ExampleView: View {

private let pageTitle = "Page Title"

#if !os(macOS)
public var body: some View {
main.navigationBarTitle(Text(pageTitle))
}
#else
public var body: some View {
main.frame(
minWidth: 500,
minHeight: 500
)
}
#endif
public var main: some View {

VStack(alignment: .center) {

#if os(macOS)
Text(pageTitle)
.font(.title)
#endif

Spacer()
Text("This is the view content")
Spacer()
}
}
}

SwiftUI Navigation Bar Title

It should be inside NavigationView, like

struct ContentView: View {
var body: some View {
NavigationView {
Form {
...
}
.navigationBarTitle(Text("WeSplit")) // << here !!
}
}
}

Running SwiftUI app on macOS, but the platform is recognized as iOS. Why?

Fixed the problem. The app running on macOS is a macCatalyst app, so you have to take that into consideration:

#if os(OSX)
NavigationView {
let _ = print("platform is macOS")
ProfileView()
}

#elseif os(iOS)


#if targetEnvironment(macCatalyst)
NavigationView {
let _ = print("platform is macCatalyst")
ProfileView()
}
#else
NavigationView {
let _ = print("platform is iOS")
ProfileView()
}
#endif
#endif
// platform is macCatalyst.

Different .listStyle() on iOS and WatchOS in a reusable component?

You can achieve what you want using an extension on View. This allows you to add the listStyle modifier with the parameter that you want for the OS that you want.

extension View {
public func customListStyle() -> some View {
#if os(watchOS)
return self.listStyle(PlainListStyle())
#else
return self.listStyle(InsetGroupedListStyle())
#endif
}
}

You would then use it like this:

List {
// items in list go here
}
.customListStyle()


Related Topics



Leave a reply



Submit