1.如何將一個(gè)ViewController
轉(zhuǎn)換為SwiftUI的View,引入到其他SwiftUI文件?
定義一個(gè)結(jié)構(gòu)體遵守UIViewControllerRepresentable
協(xié)議硼控,然后實(shí)現(xiàn)里面的makeUIViewController
和updateUIViewController
方法蜈块,在make
里返回需要轉(zhuǎn)換的ViewController
struct ContactsListRepresentation: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> ContactsListViewController {
ContactsListViewController()
}
func updateUIViewController(_ tableViewController: ContactsListViewController, context: Context) {
}
}
struct ContractsListViewControllerPreviews: PreviewProvider {
static var previews: some View {
ContactsListRepresentation()
}
}
這樣就將ContactsListViewController
轉(zhuǎn)換成為ContactsListRepresentation
袖瞻,后者屬于SwiftUI的View類型辙诞,可以直接引入到SwiftUI中了
import SwiftUI
struct TestSwiftUI: View {
var body: some View {
ContactsListRepresentation()
}
}
struct TestSwiftUI_Previews: PreviewProvider {
static var previews: some View {
TestSwiftUI()
}
}
2.如何將一個(gè)UIView轉(zhuǎn)換為SwiftUI里面的View,并且引入到其他SwfitUI文件量淌?
曾經(jīng)使用UIKit自定義的UIView控件骗村,如何引入SwiftUI呢,其實(shí)也很簡(jiǎn)單呀枢,只需要定義一個(gè)新的結(jié)構(gòu)體胚股,遵守UIViewRepresentable
協(xié)議
struct ContactCellRepresentable: UIViewRepresentable {
func makeUIView(context: Context) -> ContactCell {
let cell = Bundle.main.loadNibNamed("ContactCell", owner: self, options: nil)?.first as! ContactCell
return cell
}
func updateUIView(_ uiView: UIViewType, context: Context) {
}
}
struct ContactCellPreviews: PreviewProvider {
static var previews: some View {
ContactCellRepresentable()
}
}
之后就可以直接在SwiftUI文件中引入ContactCell
,他的名字變成了ContactCellRepresentable
struct TestUIViewConvertToSwiftUI: View {
var body: some View {
ContactCellRepresentable()
}
}
struct TestUIViewConvertToSwiftUI_Previews: PreviewProvider {
static var previews: some View {
TestUIViewConvertToSwiftUI()
}
}
3.如何將一個(gè)SwfitUI的View轉(zhuǎn)換為一個(gè)ViewController
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let contact = ContactInfomation.generateData().first!
let profileView = ProfileView(contact: contact)
let profileViewController = UIHostingController(rootView: profileView)
profileViewController.view.frame = view.bounds
addChild(profileViewController)
profileViewController.didMove(toParent: self)
view.addSubview(profileViewController.view)
}
}
只需要生成View裙秋,并且設(shè)置為UIHostingController
的rootView
琅拌,就可以將SwiftUI包裝成一個(gè)ViewContoller
。
此處的測(cè)試需要將SceneDelegate里的入口注釋掉
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// if let windowScene = scene as? UIWindowScene {
// let window = UIWindow(windowScene: windowScene)
// let rootView = TestSwiftUIVIewConvertToUIView()
// window.rootViewController = UIHostingController(rootView: rootView)
// self.window = window
// window.makeKeyAndVisible()
// }
// guard let _ = (scene as? UIWindowScene) else { return }
}
The Best Way to Learn is to Teach
github倉(cāng)庫(kù)地址 https://github.com/SunZhiC/LearningSwiftUI