Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to incorporate Framework SwiftUI

We can use Framework SwiftUI only from iOS 13.0+. So how to incorporate this framework from the deployment Target 10.0 or at least 12.0.

enter image description here

like image 541
Shamil Avatar asked Jun 06 '19 21:06

Shamil


2 Answers

Although @DenFav is absolutely right - supporting deployment target below iOS 13 with SwiftUI is a pain, but it is possible.

Steps:

  1. Link the framework weakly (I used this answer):

    Adding -weak_framework SwiftUI to Other Linker Flags fixed my issue

  2. Wrap all SwiftUI calls with canImport (see answer):

    #if canImport(SwiftUI) && canImport(Combine)

This will allow you to build and archive with deployment target < iOS 13.

Optional:

Now the question is: how to deal with viewModels. I solved this with my own implementation. You can check the solution in the public repo of Ruuvi Station. Note: the code is complex (VIPER), that's why I'll shortly describe the main ideas.

The viewModel implementation is in Classes/Presentation/Binding.

I'm using these viewModels, wrapping them with ObservableObject for SwiftUI.

You can still observe changes made in SwiftUI code.

The result is: iOS 13 uses SwiftUI code for Presentation Layer, while iOS 12 and lower is using traditional UIKit code.

The viewController is responsible for determining if SwiftUI code can be used.

like image 70
Renatus Avatar answered Oct 19 '22 10:10

Renatus


Build Phases → Link Binary With Libraries → Add SwiftUI.framework (Status: Optional)

import SwiftUI

@available(iOS 13.0, *)
struct SwiftUIView : View {
    var body: some View {
        Text("Hello World!")
    }
}

@available(iOS 13.0, *)
struct SwiftUIView_Previews : PreviewProvider {
    static var previews: some View {
        SwiftUIView()
    }
}

etc.

SwiftUI preview for this target doesnʼt work, but you can add a special target “SwiftUI Preview”.

like image 36
Roman Kerimov Avatar answered Oct 19 '22 12:10

Roman Kerimov