代码之家  ›  专栏  ›  技术社区  ›  TechChain

如何在swift中的uiCollectionView中添加分页?

  •  3
  • TechChain  · 技术社区  · 7 年前

    我有一个显示项目的uicollection视图。现在我想在uiCollectionView上添加分页。我不想将任何第三方用于此功能。请让我知道我是如何做到这一点的!

    我有四个一个例子 http://slicode.com/bottom-refresh-control-uicollectionview/

    但在这里,我必须向上拖动滚动视图几秒钟,才能使其工作。

    8 回复  |  直到 7 年前
        1
  •  2
  •   Jaydeep Vora    7 年前

    如果要添加底部刷新控件,必须使用下面的帮助器类。

    https://github.com/vlasov/CCBottomRefreshControl/tree/master/Classes

    下载Objective-C中的这2个文件。您必须在桥接头中导入该文件。

    #import "UIScrollView+BottomRefreshControl.h"
    

    像这样添加刷新控件。

    let refreshControl = UIRefreshControl.init(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
    refreshControl.triggerVerticalOffset = 50.0 
    refreshControl.addTarget(self, action: #selector(paginateMore), for: .valueChanged) 
    collectionView.bottomRefreshControl = refreshControl
    

    这个助手类为您提供了新的 bottomRefreshControl 属性,它帮助您在底部添加刷新控件。

        2
  •  2
  •   Chirag Shah    7 年前

    我已经在我的一个应用程序中添加了加载更多的功能,所以让我向您提供代码

        func collectionView(_ collectionView: UICollectionView, layout
            collectionViewLayout: UICollectionViewLayout,
                            referenceSizeForFooterInSection section: Int) -> CGSize {
    
            if arrData.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 == UICollectionElementKindSectionFooter {
    
                let vew = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "footer", for: indexPath)
    
    
                let loading = UIActivityIndicatorView()
                loading.activityIndicatorViewStyle = .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 == UICollectionElementKindSectionFooter {
    
                if let loadingView = view.viewWithTag(-123456) as? UIActivityIndicatorView{
                    if arrData.count > 0 && isLastPageReached == false 
                    {
                        loadingView.startAnimating()
                        self.loadMore()
                    }
                    else
                    {
                        self.isLoadMore = false
                    }
                }
            }
        }
        func collectionView(_ collectionView: UICollectionView, didEndDisplayingSupplementaryView view: UICollectionReusableView, forElementOfKind elementKind: String, at indexPath: IndexPath) {
            if elementKind == UICollectionElementKindSectionFooter{
    
                if let loadingView = view.viewWithTag(-123456) as? UIActivityIndicatorView{
                    loadingView.stopAnimating()
                    loadingView.removeFromSuperview()
    
                    self.isLoadMore = false
                }
    
            }
        }
    
        3
  •  2
  •   Pranavan SP    7 年前

    CollectionView委托方法:在CollectionView上按滚动要求加载更多数据。

    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
            if indexPath.row == numberofitem.count - 1 {  //numberofitem count
                updateNextSet()  
            }
    }
    
    func updateNextSet(){
           print("On Completetion")
           //requests another set of data (20 more items) from the server.
    }
    
        4
  •  1
  •   Sanjukta    7 年前

    请试试这个,它对我有用。

    步骤1:

    声明全局变量:

    var totalCount : NSInteger?
    var isGetResponse : Bool = true
    var activityIndiator : UIActivityIndicatorView?
    

    设置VIEWDIDLOAD:

    activityIndiator = UIActivityIndicatorView(frame: CGRect(x: self.view.frame.midX - 15, y: self.view.frame.height - 140, width: 30, height: 30))
        activityIndiator?.activityIndicatorViewStyle = .white
        activityIndiator?.color = UIColor.black
        activityIndiator?.hidesWhenStopped = true
        activityIndiator?.backgroundColor = COLOR.COLOR_TABLEVIEW_BACKGROUND
        activityIndiator?.layer.cornerRadius = 15
        self.view.addSubview(activityIndiator!)
        self.view.bringSubview(toFront: activityIndiator!)
    

    第2步: 在API调用方法中设置值:

    self.totalCount = array.count
    self.isGetResponse = true
    

    第3步: 编写此代码:

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
    
    
    if isGetResponse {
        if (scrollView.contentOffset.y == scrollView.contentSize.height - scrollView.frame.size.height)
        {
            if totalArrayCount! > self.arrProductListing.count{
    
                    isGetResponse = false
                    activityIndiator?.startAnimating()
                    self.view.bringSubview(toFront: activityIndiator!)
                    pageIndex = pageIndex + 1
                    print(pageIndex)
                    self.getProductListing(withPageCount: pageIndex)
                }
            }
    
            //LOAD MORE
            // you can also add a isLoading bool value for better dealing :D
        }
    }
    

    在服务调用中,您可以发送页面索引,并从服务器端发送响应。

    谢谢您。

        5
  •  1
  •   Ketan Odedra ikbal    7 年前

    简单的方法

     var page:Int = 0
     var isPageRefreshing:Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        YourApi(page1: 0)
    }
    
     func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if(self.mycollectionview.contentOffset.y >= (self.mycollectionview.contentSize.height - self.mycollectionview.bounds.size.height)) {
            if(isPageRefreshing==false) {
                isPageRefreshing=true
                print(page)
                page = page + 1
                YourApi(page1: page)
            }
        }
    }
    

    在您的API方法中

    func YourApi(page1 :Int) {
        let mypage = String(page1)
        let Request: String = String.init(format:"apiName/%@",mypage)
        print(Request)
    }
    

    就这样。

        6
  •  0
  •   Mohsenasm    7 年前

    中的代码 willDisplay cell 方法调用LoadMore函数,而滚动距离末尾5个单元格。获取数据时,在集合视图页脚中显示加载程序。加载完成后隐藏页脚。

    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {        
            let currentPage = collectionView.contentOffset.y / collectionView.frame.size.width;
            if (aryDataSource.count >= yourAPIResponsebatchCount && aryDataSource.count - indexPath.row == 5 && currentPage >= currentPage && isDataLoading) {
                currentPage++;
                self.fetchMoreData()
            }
            else { }
    }
    
        7
  •  0
  •   Cemal BAYRI    7 年前

    我在分页时使用了这个代码。 重点是:在集合视图加载和控制它的mod时捕获已加载的单元格索引,并使用API中的page-size字段(如果有)分别获取数据。您可以决定哪个数字比这个计算小,并控制它。

    例如,您获取了5个数据并加载了它,如果此状态正常,您将获取其他5个数据。这是这个的示例代码。

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
            if let vc = self.parentViewController as? SellController {
                if vc.dontFetch == false {
                    DispatchQueue.main.async {
                        if self.salesData.count > 3 {
                            if indexPath.row != 1 {
                                if indexPath.row % 3 == 1 {
                                    print("indexpath: \(indexPath.row)")
                                    vc.pagination += 1
                                    vc.reload()
    
                                }
                            }
                        }
                    }
                }
            }
        }
    

    在这段代码中,我正在控制indexpath.row%3==1或不。它可能有点复杂,所以如果您需要,我可以共享一个代码块。祝你好运:)

        8
  •  0
  •   Shezad    7 年前

    —— 项目列表 -您的数据数组。

    —— 页数 -用于跟踪页数的变量。

    —— 总计数 -数据总数

    ---将数据附加到 项目列表 每次调用API时。

    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        if indexPath.row == itemList.count - 1 && itemList.count < totalCount{
            pageCount += 1
            // Call API here
        }
    }