🛩️
SwiftUIを使いつつターゲットOSをiOS11まで下げられるAltSwiftUIでHello, Worldする
環境構築
- Life CycleをSwiftUI AppではなくUIKit App Delegateにしてプロジェクト作成
- AltSwiftUIをpodインストール
$ pod init- Podfileに
pod 'AltSwiftUI'を追加 $ pod install
-
.xcworkspaceプロジェクトファイルを開く
コード修正
AltSwiftUIをimportした時に発生するエラーを消すための作業
-
ContentView.swiftの編集- 元々あったSwiftUIは消してライブラリ本体やプロトコルをimport
ContentView- import SwiftUI + import AltSwiftUI + import protocol SwiftUI.PreviewProvider + import protocol AltSwiftUI.View-
ContentViewの編集-
someを消してviewStoreを定義
ContentViewstruct ContentView: View { + var viewStore = ViewValues() - var body: some View { + var body: View { Text("Hello, world!") .padding() } } -
-
ContentView_Previewsの編集-
AltPreviewProviderプロトコルを追加で適合させる
ContentView- struct ContentView_Previews: PreviewProvider { + struct ContentView_Previews: AltPreviewProvider, PreviewProvider { - static var previews: some View { + static var previewView: View { ContentView() } } -
-
AppDelegate.swiftの編集-
AltSwiftUIのimportAppDelegate+ import AltSwiftUI - 以下のプロパティを定義AppDelegate
+ var window: UIWindow? + private var mainController: UIViewController? - didFinishLaunchingWithOptionsを引数に持つapplication関数内で以下を記述AppDelegate
+ window = UIWindow() + mainController = UIHostingController(rootView: ContentView()) + window?.rootViewController = mainController + window?.makeKeyAndVisible()
-
-
SceneDelegate.swiftの編集- エラーが発生しているscene関数のコードブロックをコメントアウトor消す
- ここまでで全てのエラーは解消し、ビルドが通ることでPreviewも見れるはず
シミュレーターor実機で動かすために追加のセットアップ
-
AltSwiftUIをimportSceneDelegate+ import AltSwiftUI - 以下のプロパティを定義SceneDelegate
+ var window: UIWindow? + private var mainController: UIViewController? - scene関数に以下のコードを追加SceneDelegate
+ if let windowScene = scene as? UIWindowScene { + window = UIWindow(windowScene: windowScene) + mainController = UIHostingController(rootView: ContentView()) + window?.rootViewController = mainController + window?.makeKeyAndVisible() + }
ビルドターゲットを下げた時に発生するエラーの対処
- Hello, Worldの規模であれば
SceneDelegateクラスの先頭行に@available(iOS 13.0, *)を追加するとファイル全体に発生していたエラーは消える-
AppDelegateにもエラーが出ている場合は該当コードをコメントアウトする
iOS12.4のシミュレーターでアプリを実行
-
Discussion