Filipe Sá
Filipe Sá

Reputation: 382

SwiftUI: Type does not conform to protocol 'UIViewRepresentable'

I'm developing a new SwiftUI app and I'm trying to figure out how to make this Swift project compatible with SwiftUI: https://github.com/suzuki-0000/SKPhotoBrowser

The problem is that I can't make the UIViewRepresentable work. I get an error:

Type 'PhotoViewer' does not conform to protocol 'UIViewRepresentable'

Here is my code:

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
        }

    }
}

What am I missing here?

Upvotes: 9

Views: 23029

Answers (1)

Asperi
Asperi

Reputation: 257701

The SKPhotoBrowser is a UIViewController subclass, so you need to conform it to UIViewControllerRepresentable not UIViewRepresentable

Actually, not much differences:

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
        }

    }
}

Upvotes: 13

Related Questions