Как представить UICollectionView в SwiftUI с помощью UIViewControllerRepresentable - PullRequest
4 голосов
/ 25 апреля 2020

Во-первых, я знаю, что есть варианты использования SwiftUI Lists et c ... для получения похожих эффектов. Но мне нужны автоматические возможности прокрутки c в UICollectionView, поэтому я действительно хотел бы просто реализовать версию "старой школы". Я даже не хочу идеальную композиционную версию макета.

Мой текущий код выглядит так:

import SwiftUI

struct CollectionView: UIViewControllerRepresentable {

private var isActive: Binding<Bool>
private let viewController = UIViewController()
private let collectionController: UICollectionView

init(_ isActive: Binding<Bool>) {
    self.isActive = isActive
    self.collectionController = UICollectionView(frame: CGRect(x: 0, y: 0, width: 100, height: 200), collectionViewLayout: UICollectionViewFlowLayout())
}
func makeUIViewController(context: UIViewControllerRepresentableContext<CollectionView>) -> UIViewController {
    return viewController
}

func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<CollectionView>) {
    if self.isActive.wrappedValue && collectionController.delegate == nil { // to not show twice
        collectionController.delegate = context.coordinator
        collectionController.dataSource = context.coordinator
    }
}

func makeCoordinator() -> Coordintor {
    return Coordintor(owner: self)
}

final class Coordintor: NSObject, UICollectionViewDelegate, UICollectionViewDataSource {
    weak var viewController:UIViewController?
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 3
    }
    var cellId = "Cell"
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
        return cell
    }
    // works as delegate
    let owner: CollectionView
    init(owner: CollectionView) {
        self.owner = owner

    }
}
}

К сожалению, все, что я получаю, это пустой экран в окне предварительного просмотра. На данный момент, если я могу просто отобразить большой выбор красных квадратов, которые я могу прокручивать и автоматически прокручивать до нижней части на Appar, это было бы идеально.

Спасибо!

1 Ответ

1 голос
/ 02 мая 2020

Здесь минимальная работоспособная демоверсия. ( Примечание: ячейка должна быть зарегистрирована, если все сделано программно )

demo

class MyCell: UICollectionViewCell {
}

struct CollectionView: UIViewRepresentable {
    func makeUIView(context: Context) -> UICollectionView {
        let view = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
        view.backgroundColor = UIColor.clear
        view.dataSource = context.coordinator

        view.register(MyCell.self, forCellWithReuseIdentifier: "myCell")
        return view
    }

    func updateUIView(_ uiView: UICollectionView, context: Context) {
    }

    func makeCoordinator() -> Coordinator {
        Coordinator()
    }

    class Coordinator: NSObject, UICollectionViewDataSource {
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            3
        }

        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! MyCell
            cell.backgroundColor = UIColor.red
            return cell
        }
    }
}

struct TestUICollectionView_Previews: PreviewProvider {
    static var previews: some View {
        CollectionView()
    }
}
...