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.
Deep Learning is a subfield of machine learning concerned with algorithms inspired by the structure…
How LSTM works? I think it’s unfair to say that neural network has no memory…
What is Deep Learning? Deep Learning is a new area of Machine Learning research, which…
Generative AI refers to a category of advanced algorithms designed to produce original content across…
Generative AI Video Tools Everyone Should Know About Generative AI is revolutionizing video creation, making…
Large Language Models (LLMs) are a transformative advancement in artificial intelligence, capable of understanding, processing,…