美文网首页程序员iOS开发
SwiftUI:SwiftUI项目中调用UIKit(如:UIVi

SwiftUI:SwiftUI项目中调用UIKit(如:UIVi

作者: 心猿意码_ | 来源:发表于2023-01-06 15:47 被阅读0次
1、在SwiftUI中使用UIKit控件,需要遵循以下协议:
  • UIView使用需要遵循UIViewRepresentable协议。

  • UIViewController使用需要遵循UIViewControllerRepresentable协议

  • 效果展示:(传值:背景颜色)
1.gif
代码如下:
import SwiftUI



struct ContentView: View {
    
    @State var isPush = false
    
    var body: some View {
        NavigationView {
            
            VStack {
                
                NavigationLink(isActive: $isPush) {
                    TestTempVC(color: .red)
                }label: {
                    
                }
                
                Button {
                    isPush = true
                } label: {
                    Text("跳转到TestVC")
                }

            }.navigationBarTitle("ContentView", displayMode: .inline)
            .padding()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
import UIKit
import SwiftUI

// 遵循UIViewControllerRepresentable协议
struct SwiftUICallSwift: UIViewControllerRepresentable {
    var color : UIColor?
    func makeUIViewController(context: Context) -> some UIViewController {
        let vc = TestViewController()
        vc.color = color
        return vc
    }
    
    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
        
    }
    
}

// SwiftUI(此处的作用是为了设置导航,如果直接从上个页面push到TestViewController,导航返回按钮点击将无效)
struct TestTempVC: View {
    @Environment(\.presentationMode) var presentationMode
    @State var color : UIColor?
    
    var body: some View{
        VStack{
            SwiftUICallSwift(color: color)
        }.navigationBarTitle("TestViewController", displayMode: .inline)
            .navigationBarBackButtonHidden(true)
            .navigationBarItems(leading: Button(action: {
                presentationMode.wrappedValue.dismiss()
            }, label: {
                Image("nav_back_black")
            }))
    }
}

// UIViewController
class TestViewController: UIViewController {
    
    var color : UIColor?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = color ?? .orange
        
        self.title = "TestVC"
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 50))
        label.textAlignment = .center
        label.center = self.view.center
        label.text = "这是一个Swift的ViewController"
        self.view.addSubview(label)
        
    }

}

以上就是swiftUI调用swift的UIkit使用

相关文章

网友评论

    本文标题:SwiftUI:SwiftUI项目中调用UIKit(如:UIVi

    本文链接:https://www.haomeiwen.com/subject/wamscdtx.html