Swift 和 SwiftUI混编

329 阅读1分钟

1、UIHostingController将SwiftUI视图转化为Swift的VC

import UIKit
import SwiftUI

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let popup = UIButton(type: .system)
        popup.setTitle("Popup SwiftUI View", for: .normal)
        popup.setTitleColor(.orange, for: .normal)
        popup.titleLabel?.font = UIFont.systemFont(ofSize: 36)
        popup.sizeToFit()
        popup.center = self.view.center
        popup.addTarget(self, action: #selector(popupController), for: .touchUpInside)
        
        self.view.addSubview(popup)
    }
    
    @objc func popupController()
    {
        let vc = UIHostingController(rootView: ContentView())
        self.present(vc, animated: true, completion: nil)
    }
}