簡體   English   中英

如何在 UIViewRepresentable SwiftUI 中重新加載 collectionview

[英]How to reload collectionview in UIViewRepresentable SwiftUI

## 如何在 UIViewRepresentable 中重新加載集合視圖 ##

使用 UIViewRepresentable 和集合視圖,在迭代后遇到 reload() 集合視圖時卡住了,如何在執行數據迭代時在 UIViewRepresentable 中重新加載集合視圖? func updateUIView 不起作用。


    struct VideoCollectionView: UIViewRepresentable {

        var data: VideoViewModel

        @Binding var search: String

        var dataSearch: [VideoPostModel] {
            if search.isEmpty {
                return data.postsSearch
            }else{
                let d = data.postsSearch.filter {$0.artistname.localizedStandardContains(search)}
                return d
            }
        }

        var didSelectItem: ((_ indexPath: IndexPath)->()) = {_ in }
        var didSelectObject: ((_ boject: VideoPostModel)->()) = {_ in }

        func makeUIView(context: Context) -> UICollectionView {
            let reuseId = "AlbumPrivateCell"

            let collection :UICollectionView = {
                let layout = UICollectionViewFlowLayout()
                layout.sectionHeadersPinToVisibleBounds = true
                let collectionV = UICollectionView(frame: .zero, collectionViewLayout: layout)
                layout.scrollDirection = .vertical
                collectionV.translatesAutoresizingMaskIntoConstraints = false
                collectionV.backgroundColor = .clear
                collectionV.dataSource = context.coordinator
                collectionV.delegate = context.coordinator
                collectionV.register(AlbumPrivateCell.self, forCellWithReuseIdentifier: reuseId)

                return collectionV
            }()

            return collection
        }
        func updateUIView(_ collectionView: UICollectionView, context: UIViewRepresentableContext<VideoCollectionView>) {
            print("updateUIView updateUIView")
            print(search)

            collectionView.reloadData() 
        }
        func makeCoordinator() -> Coordinator {
            Coordinator(self)
        }

        class Coordinator: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

            private var parent: VideoCollectionView
            init(_ albumGridView: VideoCollectionView) {
                self.parent = albumGridView
            }
            func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
                return self.parent.dataSearch.count
            }
            func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AlbumPrivateCell", for: indexPath) as! AlbumPrivateCell
                    cell.data = self.parent.dataSearch[indexPath.item]
                return cell
            }
            func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
                let post = self.parent.dataSearch[indexPath.item]
                parent.didSelectItem(indexPath)
                parent.didSelectObject(post)
            }
            func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
                let width = collectionView.frame.width
                let height = collectionView.frame.height/2
                return CGSize(width: width, height: height)
            }

        }
    }

現在處理這個問題,我能夠制作 reloadData 的唯一方法是在我的 Coordinator 類中創建一個引用並在創建時傳遞它:

context.coordinator.collectionView = collectionView

從那里你可以調用 reloadData(),當然有更優雅的方法來解決這個問題。

編輯:回答請求以擴展我的方法。

假設您有一個這樣的協調員:

class CoordinatorItemPicturesView: NSObject, UICollectionViewDataSource, UICollectionViewDelegate {
// MARK: - Properties
var collectionView: UICollectionView!
var elements = [String]()
init(elements:[String]) {
    self.elements = elements
}

// MARK: UICollectionViewDataSource

func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int {
    return elements.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    return  UICollectionViewCell()
}
}

因此,當您創建 UIViewRepresentable 時,請傳遞 collectionView 引用:

struct ItemPicturesView: UIViewRepresentable {
func makeUIView(context: UIViewRepresentableContext<ItemPicturesView>) -> UICollectionView {
    /// Set Context, cells, etc
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    collectionView.backgroundColor = .clear
    collectionView.translatesAutoresizingMaskIntoConstraints = false
    collectionView.dataSource = context.coordinator
    collectionView.delegate = context.coordinator
    collectionView.isScrollEnabled = true
    // --- Right here
    context.coordinator.collectionView = collectionView
    return collectionView
}

func updateUIView(_ uiView: UICollectionView, context _: Context) {
    UIView.animate(withDuration: 1.0) {
        uiView.frame = uiView.frame
        uiView.reloadData()
    }
}

func makeCoordinator() -> CoordinatorItemPicturesView {
    CoordinatorItemPicturesView(elements:["Element One", "Element Two"])
}
}

對不起,如果代碼不是 100% 完美,則必須從帶有 NDA 的項目中獲取它並且沒有使用已刪除的屬性進行測試。

UIViewRepresentable 只是一個包裝器。 您必須將您的模型設為 Observable。 然后它會在數據發生任何變化時自動更新。

您需要做的就是將VideoCollectionViewdata屬性VideoCollectionView為:

@Binding var data: VideoViewModel

現在一旦你更新數據,你更新視圖將重新加載 collectionView。 說明:您的數據屬性(值類型)應該是 Binding 屬性,因為Coordinator依賴於此。 當您使用 self 初始化 Coordinator 時,您正在傳遞數據屬性的舊實例。 將其更改為綁定允許它發生變異。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM