我正在开发一个新的 SwiftUI 应用程序,并试图弄清楚如何使这个 Swift 项目与 SwiftUI 兼容:
https://github.com/suzuki-0000/SKPhotoBrowser
问题是我无法使 UIViewRepresentable 工作。
我收到一个错误:
Type 'PhotoViewer' does not conform to protocol 'UIViewRepresentable'
这是我的代码:
struct PhotoViewer: UIViewRepresentable {
@Binding var viewerImages:[SKPhoto]
@Binding var currentPageIndex: Int
func makeUIView(context: Context) -> SKPhotoBrowser {
let browser = SKPhotoBrowser(photos: viewerImages)
browser.initializePageIndex(currentPageIndex)
browser.delegate = context.coordinator
return browser
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func updateUIView(_ browser: SKPhotoBrowser, context: Context) {
browser.photos = viewerImages
browser.currentPageIndex = currentPageIndex
}
class Coordinator: NSObject, SKPhotoBrowserDelegate {
var control: PhotoViewer
init(_ control: PhotoViewer) {
self.control = control
}
func didShowPhotoAtIndex(_ browser: PhotoViewer) {
self.control.currentPageIndex = browser.currentPageIndex
}
}
}
我在这里想念什么?
最佳答案
SKPhotoBrowser
是 UIViewController
子类,因此您需要使其符合 UIViewControllerRepresentable
不是 UIViewRepresentable
其实差别不大:
struct PhotoViewer: UIViewControllerRepresentable {
@Binding var viewerImages:[SKPhoto]
@Binding var currentPageIndex: Int
func makeUIViewController(context: Context) -> SKPhotoBrowser {
let browser = SKPhotoBrowser(photos: viewerImages)
browser.initializePageIndex(currentPageIndex)
browser.delegate = context.coordinator
return browser
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func updateUIViewController(_ browser: SKPhotoBrowser, context: Context) {
browser.photos = viewerImages
browser.currentPageIndex = currentPageIndex
}
class Coordinator: NSObject, SKPhotoBrowserDelegate {
var control: PhotoViewer
init(_ control: PhotoViewer) {
self.control = control
}
func didShowPhotoAtIndex(_ browser: PhotoViewer) {
self.control.currentPageIndex = browser.currentPageIndex
}
}
}
关于SwiftUI:类型不符合协议(protocol) 'UIViewRepresentable',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61483839/