UICollectionView不能垂直分页

时间:2018-11-19 06:41:34

标签: ios swift uicollectionview

我正在开发一个应用程序,该应用程序从后端API获取100个数据,我在collectionView中显示此数据,但是一次显示100个数据可能会很长而且很烦人,所以我想为了通过我的研究实现对UICollectionView的分页,我尝试实现一些代码行,但是当我向上滚动时,什么也看不到。没有UIActivityIndicator不显示任何内容。我已经连续搜索了三天,但没有任何积极的结果。我在下面粘贴了我的代码,希望有人能提供帮助。预先感谢

class MainVC: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!
    @IBAction func prepareForUnwind(segue: UIStoryboardSegue) {}
    @IBOutlet weak var spinner: UIActivityIndicatorView!

    var itemArray = OfflineFunctions.instance.getDataFromDB()
    var flickrArray = ServiceProvider.instance.flickerPhotos // This returns 100 items

    var offline: Bool = false
    var isLoadMore: Bool = false
    var isLastPageReached: Bool = false
    var limit = 10
    let totalEntries = ServiceProvider.instance.flickerPhotos.count // This returns 100 items

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.delegate = self
        collectionView.dataSource = self
        setupWithPhotos()
        collectionView.isPagingEnabled = true

    }


    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        collectionView.reloadData()
    }

    // Function that gets the items 

    func setupWithPhotos() -> Void {

        spinner.isHidden = false
        spinner.startAnimating()

        ServiceProvider.instance.getPhotos {[weak self] (success, error) in
            if success {
                self?.collectionView.reloadData()
                self?.spinner.isHidden = true
                self?.spinner.stopAnimating()

                self?.offline = false
            }

            if error != nil {

                alert.addAction(UIAlertAction(title: "Ok", style: .cancel) { (action:UIAlertAction!) in
                    self?.spinner.isHidden = true
                    self?.spinner.stopAnimating()
                    self?.collectionView.reloadData()
                    self?.offline = true
                })

                self?.present(alert, animated: true)
            }
        }
    }

    @IBAction func reloadPressed(_ sender: Any) {
        setupWithPhotos()
    }

    @IBAction func closePressed(_ sender: Any) {
        performSegue(withIdentifier: UNWIND, sender: nil)
    }

    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        targetContentOffset.pointee = scrollView.contentOffset
        var indexes = self.collectionView.indexPathsForVisibleItems
        indexes.sort()
        var index = indexes.first!
        let cell = self.collectionView.cellForItem(at: index)!
        let position = self.collectionView.contentOffset.y - cell.frame.origin.y
        if position > cell.frame.size.height/2{
            index.row = index.row+1
        }
        self.collectionView.scrollToItem(at: index, at: .left, animated: true )
    }

}

extension MainVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

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


        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PHOTO_CELL, for: indexPath) as? MainCell {

            cell.offline = offline
            if !offline {

                 let flickerPhoto = ServiceProvider.instance.flickerPhotos[indexPath.row]
                cell.configueCell(flickerPhotoModel: flickerPhoto, index: indexPath.item)
                return cell
            } else {

                let flickerPhoto = itemArray[indexPath.row]
                cell.configueOfflineCell(flickerPhotoModel: flickerPhoto, index: indexPath.item)
                return cell
            }
        }
        return MainCell()
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if !offline {
            return ServiceProvider.instance.flickerPhotos.count
        } else {
            return itemArray.count
        }

    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        // setting cells based on screen size

        var numOfColums : CGFloat = 2
        if UIScreen.main.bounds.width > 320 {
            numOfColums = 1
        }

        let spaceBtwCells : CGFloat = 10
        let padding: CGFloat = 40
        let cellDimension = ((collectionView.bounds.width - padding) - (numOfColums - 1) * spaceBtwCells) / numOfColums

        return CGSize(width: cellDimension, height: cellDimension)

    }



    func collectionView(_ collectionView: UICollectionView, layout
        collectionViewLayout: UICollectionViewLayout,
                        referenceSizeForFooterInSection section: Int) -> CGSize {

        if flickrArray.count > 0 && isLastPageReached == false {
            return CGSize(width:(collectionView.frame.size.width), height: 100.0)
        }
        return CGSize.zero

    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        if kind == UICollectionView.elementKindSectionFooter {

            let vew = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "footer", for: indexPath)


            let loading = UIActivityIndicatorView()
            loading.style = .gray
            loading.translatesAutoresizingMaskIntoConstraints = false
            loading.tintColor = UIColor.gray
            loading.tag = -123456
            vew.addSubview(loading)
            vew.addConstraint(NSLayoutConstraint(item: loading, attribute: .centerX, relatedBy: .equal, toItem: vew, attribute: .centerX, multiplier: 1, constant: 0))
            vew.addConstraint(NSLayoutConstraint(item: loading, attribute: .centerY, relatedBy: .equal, toItem: vew, attribute: .centerY, multiplier: 1, constant: 0))


            return vew
        }
        return UICollectionReusableView()
    }

    func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {
        if elementKind == UICollectionView.elementKindSectionFooter {

            if let loadingView = view.viewWithTag(-123456) as? UIActivityIndicatorView{
                if flickrArray.count > 0 && isLastPageReached == false {
                    loadingView.startAnimating()
                    print("END REACH 1")
                }
                else {
                    self.isLoadMore = false
                }
            }
        }
    }

    func collectionView(_ collectionView: UICollectionView, didEndDisplayingSupplementaryView view: UICollectionReusableView, forElementOfKind elementKind: String, at indexPath: IndexPath) {
        if elementKind == UICollectionView.elementKindSectionFooter{

            if let loadingView = view.viewWithTag(-123456) as? UIActivityIndicatorView{
                loadingView.stopAnimating()
                loadingView.removeFromSuperview()

                self.isLoadMore = false
            }

        }
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {


        if !offline {
            let flickerPhoto = ServiceProvider.instance.flickerPhotos[indexPath.item]
            ServiceProvider.instance.selectedPhoto = flickerPhoto
            performSegue(withIdentifier: DETAIL_VC_SEGUE, sender:indexPath)
        } else {
            let offlineList = OfflineFunctions.instance.offlineItems?[indexPath.item]
            OfflineFunctions.instance.selectedImage = offlineList
            performSegue(withIdentifier: MAIN_TO_SAVED_DETAIL_VC_SEGUE, sender:indexPath)
        }
        NotificationCenter.default.post(name: NOTIFY_PHOTO_SELECTED, object: nil)


    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == SAVED_DETAIL_VC) {

            let popUp = segue.destination as! SavedDetailVC
            popUp.doneSaving = { [weak self] in
                self?.collectionView.reloadData()
            }

        }
    }

}

这是我的API获取https://www.flickr.com/services/api/explore/flickr.photos.getRecent的链接 根据要求可以添加更多代码

0 个答案:

没有答案