【问题标题】:Horizontal direction UICollectionView with UIRefreshControl reloadData() not working带有 UIRefreshControl reloadData() 的水平方向 UICollectionView 不起作用
【发布时间】:2019-11-04 05:19:57
【问题描述】:

我需要实现水平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
    }
}

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

【问题讨论】:

    标签: ios swift uicollectionview swift4 uirefreshcontrol


    【解决方案1】:

    collectionViewalwaysBounceVertical属性设置为viewDidLoad()中的true,即

    collectionView.alwaysBounceVertical = true
    

    【讨论】:

      猜你喜欢
      • 2013-06-20
      • 1970-01-01
      • 2018-03-26
      • 1970-01-01
      • 1970-01-01
      • 2018-11-09
      • 1970-01-01
      • 2011-12-18
      • 2013-10-29
      相关资源
      最近更新 更多