簡體   English   中英

帶有UIRefreshControl reloadData()的水平方向UICollectionView不起作用

[英]Horizontal direction UICollectionView with UIRefreshControl reloadData() not working

我需要實現水平UICollectionView 有時,我需要更新數據,因此我決定實現一個refreshcontrol

我用refreshcontrol調用了reloadData() 它似乎正在工作,但是cellForItemAt沒有被稱為正確的時間。 因此,當單元數更改時,它將崩潰。

class ViewController: UIViewController, UICollectionViewDelegate {


    @IBOutlet weak var collectionView: UICollectionView!

    private let refreshControl = UIRefreshControl()
    private var cellCount = 1

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.delegate = self
        collectionView.dataSource = self

        collectionView.refreshControl = refreshControl
        refreshControl.addTarget(self, action: #selector(refresh(sender:)), for: .valueChanged)

        collectionView.register(UINib(nibName: "TopCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "Cell")

        if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.scrollDirection = .horizontal // not working
//            layout.scrollDirection = .vertical //working
        }
    }

    @objc func refresh(sender: UIRefreshControl) {
        cellCount = cellCount + 1
        collectionView.reloadData()
        sender.endRefreshing()
    }
}

extension ViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return cellCount
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: TopCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! TopCollectionViewCell

        return cell
    }
}

如果方向更改為垂直,則說明它正在工作。 這是正確的行為嗎? 還是一個錯誤?

viewDidLoad() alwaysBounceVertical collectionViewalwaysBounceVertical屬性設置為true ,即

collectionView.alwaysBounceVertical = true

暫無
暫無

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

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