【问题标题】:SwiftUI: Type does not conform to protocol 'UIViewRepresentable'SwiftUI:类型不符合协议“UIViewRepresentable”
【发布时间】:2020-04-28 15:21:01
【问题描述】:

我正在开发一个新的 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
        }

    }
}

我在这里错过了什么?

【问题讨论】:

    标签: swift xcode swiftui


    【解决方案1】:

    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
            }
    
        }
    }
    

    【讨论】:

      【解决方案2】:

      也许您忘记明确指定 UIViewType 的类型别名?

      【讨论】:

      • @FilipeSá 啊,你忘了typealias UIViewControllerType
      猜你喜欢
      • 2021-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-23
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多