SwiftUI3.0将UIKit ViewController转化成 swiftUI的view
Posted johnson--save
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)
以上是关于SwiftUI3.0将UIKit ViewController转化成 swiftUI的view的主要内容,如果未能解决你的问题,请参考以下文章