其他分享
首页 > 其他分享> > SwiftUI3.0将UIKit ViewController转化成 swiftUI的view

SwiftUI3.0将UIKit ViewController转化成 swiftUI的view

作者:互联网

SwiftUI3.0将UIKit ViewController转化成 swiftUI的view 这也是SwiftUI中的重点之重。因为swiftUI里面的功能不够完善,需要借助UIKit里面的东西,就像swift 刚刚发布的时候,有时候还要借助oc的第三方类库一样。swift导入oc框架,只要搞个桥接文件即可,导入一个头文件即可。都是类似的道理。
SwiftUI3.0将UIKit ViewController转化成 swiftUI的view。,也可以将UIKit 中的view 转化成 swiftUI ,继承 UIViewRepresentable 见名知意

//
//  PageVC.swift
//  ChinaLandmark
//
//  Created by lujun on 2022/1/31.
//
import SwiftUI
struct PageVC: UIViewControllerRepresentable {
    let pages: [UIViewController]
    init(){
        pages = featuredLandmarks.map{
            UIHostingController(
                rootView:
                Image($0.imageName)
                    .resizable()
                    .scaledToFill()
            )
        }
    }
    func makeCoordinator() -> Coordinator {
        Coordinator(pages: pages)
    }
    class Coordinator : NSObject ,UIPageViewControllerDataSource{
        var pages: [UIViewController]
        init( pages: [UIViewController]){
            self.pages = pages
            super.init()
        }
        func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
             let currentIndex =  pages.firstIndex(of: viewController)!
            return currentIndex == 0 ? pages.last : pages[currentIndex - 1]
        }
        func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
            let currentIndex = pages.firstIndex(of: viewController)!
            return currentIndex == pages.count - 1 ?  pages.first : pages[currentIndex + 1]
        }
    }
    
    func makeUIViewController(context: Context) -> UIPageViewController{
        let pageVC = UIPageViewController.init(transitionStyle: .scroll, navigationOrientation: .horizontal)
//        pageVC.delegate = self
        //从上下文获取 coordinator 的 datasource
        pageVC.dataSource = context.coordinator
        //类似这种写法
//        pageVC.dataSource = Coordinator(pages)
        return pageVC
    }
    func updateUIViewController(_ uiViewController: UIPageViewController, context: Context) {
        uiViewController.setViewControllers([pages[0]], direction: .forward, animated: true)
    }
}

标签:UIKit,UIPageViewController,ViewController,SwiftUI3.0,pages,swiftUI,currentIndex,
来源: https://www.cnblogs.com/Johnson-Swift/p/15858846.html