【iOS】SwiftUI使用UIViewController

Share
摘自

https://sarunw.com/posts/uiviewcontroller-in-swiftui/

步骤:
1.遵循UIViewControllerRepresentable协议;
2.实现对应的两个代理方法makeUIViewController()updateUIViewController().

实现:
1.先创建一个UIViewController用于之后的SwiftUI

class MyViewController: UIViewController {
    // 1
    private var label: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.font = UIFont.preferredFont(forTextStyle: .title1)
        label.text = "Hello, UIKit!"
        label.textAlignment = .center

        return label
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        // 2
        view.backgroundColor = .systemPink

        // 3
        view.addSubview(label)
        NSLayoutConstraint.activate([
            label.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
            label.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
            label.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
            label.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20),
        ])
    }
}

2.创建SwiftUI的结构体遵循UIViewControllerRepresentable协议;并实现其 两个代理方法,在makeUIViewController() 中返回UIViewController的实例对象;

import SwiftUI
struct MyView: UIViewControllerRepresentable {
    typealias UIViewControllerType = MyViewController

    func makeUIViewController(context: Context) -> MyViewController {
        // Return MyViewController instance
        //返回UIViewController的实例
        let vc = MyViewController()
        // Do some configurations here if needed.
        return vc
    }

    func updateUIViewController(_ uiViewController: MyViewController, context: Context) {
        // Updates the state of the specified view controller with new information from SwiftUI. 
        //从SwifitUI更新状态信息到特定UIViewController
    }
}

如果足够简单,可以使用别名指定对应的UIViewController,让Xcode自动生成实现两个代理方法;

struct MyView: UIViewControllerRepresentable {
    typealias UIViewControllerType = MyViewController    

}

3.在SwiftUI使用该View;

struct ContentView: View {
    @State var isPresented = false

    var body: some View {
        Button("MyViewController") {
            isPresented = true
        }
        .sheet(isPresented: $isPresented) {
            MyView()
                    //忽略安全区域,则页面会被完全覆盖,不保留安全区域;
                    .ignoresSafeArea()
                    //只显示100高度的View;
                    //.frame(height: 100)
        }
    }
}