SwiftUI、UIKit の相互利用について

現行のアプリにSwiftUIを用いる場合、UIKitとの相互利用について考慮する必要があるため、調べてみました。

【UIKit → SwiftUI】

UIHostingController クラス

【SwiftUI → UIKit】

UIViewRepresentable プロトコル
UIViewControllerRepresentable プロトコル

SwiftUIでUIKitのUIButtonを利用するサンプルは以下の通り

import SwiftUI

struct CounterView: View {
    @State var text: String = "Button_title"
    
    var body: some View {
        VStack(alignment: .leading) {
            CustomButton(text: $text)
        }
    }
}

struct CustomButton: UIViewRepresentable {
    @Binding var text: String

    func makeUIView(context: Context) -> UIButton {
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 200, height: 44))
        button.setTitle(self.text, for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.addTarget(context.coordinator, action: #selector(Coordinator.didTapCustomButton(sender:)), for: .touchUpInside)
        return button
    }

    // SwiftUI → UIkit
    // ビューの状態が更新されるたび呼び出される
    func updateUIView(_ uiView: UIButton, context: Context) {
        print("\(#function)")
    }

    static func dismantleUIView(_ uiView: UIButton, coordinator: ()) {
        print("\(#function)")
    }
    
    // UIKit → SwiftUI
    func makeCoordinator() -> Coordinator {
        return Coordinator(button: self)
    }

    class Coordinator {
        var button: CustomButton

        init(button: CustomButton) {
            self.button = button
        }

        @objc func didTapCustomButton(sender: UIButton) {
            print("\(#function)")
        }
    }
}

【参考】

一部の画面だけSwiftUIを使いたいとき
UIViewRepresentable を理解して SwiftUI の足りないところを UIKit で補う

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です