SwiftUI: 类型不符合协议'UIViewRepresentable'

9
我正在开发一款新的SwiftUI应用程序,我正在尝试找出如何使这个Swift项目与SwiftUI兼容: https://github.com/suzuki-0000/SKPhotoBrowser 问题是我无法让UIViewRepresentable正常工作。我得到了一个错误:
“类型'PhotoViewer'不符合协议'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
        }

    }
}

我这里错过了什么?

1个回答

12

SKPhotoBrowserUIViewController的子类,因此您需要将其符合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
        }

    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接