Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 543
Filipe Sá Avatar asked Mar 02 '23 12:03

Filipe Sá


1 Answers

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
        }

    }
}
like image 107
Asperi Avatar answered Mar 05 '23 14:03

Asperi