創建一個PageVC.swift,遵循協議UIViewControllerRepresentable
UIViewControllerRepresentable要完成兩個必選方法
func makeUIViewController(context: Context) -> UIPageViewController {
}
func updateUIViewController(_ pageVC: UIPageViewController , context: Context) {
}
得到數據
let featuredLandmarks = landmarks.filter{ $0.isFeatured }
將所有的圖片先轉換爲SwiftUIView再轉換爲UIViewController
// var pages = featuredLandmarks.map {
// UIHostingController(rootView:
// Image($0.imageName)
// .resizable()
// )
// }
var pages:[UIViewController]
init() {
//map是將featuredLandmarks所有的數據進行大括號內的操作
pages = featuredLandmarks.map {
UIHostingController(rootView:
Image($0.imageName)
.resizable()
.scaledToFill()
)
}
}
給pageVC添加dataSource
添加dataSource要遵循協議UIPageViewControllerDataSource,該協議只能在class上遵循,struct不行,所以要寫一箇中間協調源class
同時要遵循協議NSObject,再同時要完成兩個必選方法
class Coordinator: NSObject, UIPageViewControllerDataSource {
//將class外的pages傳進來
let pages: [UIViewController]
init(pages: [UIViewController]) {
self.pages = pages
}
//往左滑返回的圖片
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]
}
}
用swiftUI自帶的函數makeCoordinator提供中間協調源
func makeCoordinator() -> Coordinator {
return Coordinator(pages: pages)
}
添加dataSource
func makeUIViewController(context: Context) -> UIPageViewController {
let pageVC = UIPageViewController(
transitionStyle: .scroll,//展示效果
navigationOrientation: .horizontal//水平效果
)
//添加dataSource
// pageVC.dataSource = Coordinator(pages: pages)
pageVC.dataSource = context.coordinator//表示可以直接從上下文中獲取中間協調源
return pageVC
}
完成updateUIViewController函數
func updateUIViewController(_ pageVC: UIPageViewController , context: Context) {
pageVC.setViewControllers(
[pages[0]],//展示的第一個頁面
direction: .forward,//左劃到下一個頁面
animated: true
)
}