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

时间:2019-06-21 10:54:38

标签: ios swift uicollectionview swift4 uirefreshcontrol

我需要实现水平UICollectionView。 有时,我需要更新数据,所以我决定实现一个refreshcontrol

我用reloadData()refreshcontrol。它似乎正在工作,但是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
    }
}

如果方向更改为垂直,则说明它正在工作。 这是正确的行为吗?还是一个错误?

1 个答案:

答案 0 :(得分:1)

alwaysBounceVertical中将collectionView true 属性设置为viewDidLoad(),即

collectionView.alwaysBounceVertical = true