Let’s continue to create a project for multi-platform SwiftUI.
-SwiftUIMultiplatformApp.swift
-ContentView.swift
-Shared -> Text(“Hello, iOS/macOS!”)
-SwiftUIMultiplatform (watchOS) WatchKit Extension -> Text(“Hello, watchOS!”)
-SwiftUIMultiPlatform (tvOS) -> Text(“Hello, tvOS!”)
-Delete all except the Shared/ version of the file.
-Select the Shared/SwiftUIMultiplatformApp.swift file and add it to the tvOS and watchOS targets.
-SwiftUIMultiplatformApp (shared)
-ContentView (shared)
In a real app, we will come across cases where things can be displayed identically across all platforms and cases where we need to be platform-specific. This means we would ideally like a mixture of the two things.
To achieve this add a file called PlatformText.swift to each platform directory. Ensure it is added to the correct directory and target each time you add the file. For example, here we are adding to the iOS directory and the iOS target:
Do the same for macOS, tvOS and watchOS.
import SwiftUI struct PlatformText: View { var body: some View { Text("Hello, iOS!") } } struct PlatformText_Previews: PreviewProvider { static var previews: some View { PlatformText() } }
import SwiftUI struct ContentView: View { var body: some View { PlatformText() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
import SwiftUI struct ContentView: View { var body: some View { let platformText = PlatformText() #if os(tvOS) platformText .foregroundColor(.green) #else platformText #endif } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
The process mentioned above is a very basic demonstration of how SwiftUI can be used to share code between Apple platforms. Platform scoped files are very easy to set up, easily identifiable by directory structure and play very nicely with Xcode’s live previews. They are therefore an essential mechanism for sharing code between different platforms.
To explore more about setting up a multi-platform SwiftUI project, you can get in touch with our dedicated team of iOS developers.
In the digital age, understanding the hidden forces driving user behavior is essential. By strategically…
What is haptics? Haptics refers to the use of touch feedback technology to simulate…
In today's fast-paced and technologically driven world, businesses are constantly seeking innovative ways to stay…
The Garden State, more popularly known as New Jersey, is not only known for its…
In today's digital age, mobile apps have become an indispensable tool for businesses across all…
In today's digital era, a seamless and enjoyable user experience is crucial for the success…