Ios UICollectionView不定卷轴

Ios UICollectionView不定卷轴,ios,swift,uicollectionview,Ios,Swift,Uicollectionview,我搜索了这个主题,但找不到任何解决问题的方法。这是我的loadData函数,可以从JSON对象获取数据 @IBOutlet weak var collectionVitrin: UICollectionView! var vitrinDecodePost = [VitrinDecode]() // Decodable func loadDatas(limit : Int) { guard let url = URL(string: "my Url") else { retur

我搜索了这个主题,但找不到任何解决问题的方法。这是我的loadData函数,可以从JSON对象获取数据

 @IBOutlet weak var collectionVitrin: UICollectionView!

 var vitrinDecodePost = [VitrinDecode]() // Decodable

 func loadDatas(limit : Int) {

    guard let url = URL(string: "my Url") else { return }
    let session = URLSession.shared
    let request = NSMutableURLRequest(url: url as URL)
    request.httpMethod = "POST"
    let paramString = "limit=\(limit)"
    request.httpBody = paramString.data(using: String.Encoding.utf8)

    let task = session.dataTask(with: request as URLRequest) {
        (data, response, error) in
            guard let _:NSData = data as NSData? , let _:URLResponse = response, error == nil else {

                print("Mistake")
                return
            }

            guard let data = data else { return }
            do {

                let abc = try JSONDecoder().decode([VitrinDecode].self, from: data)
                self.vitrinDecodePost = abc

                DispatchQueue.main.async {

                    self.collectionVitrin.reloadData()
                }

            } catch { print(error)}

    }
    task.resume()
}
我在ViewDidLoad中运行此函数:

var deger : Int = 10

override func viewDidLoad() {
    super.viewDidLoad()
    loadData(limit: deger)
}
当滚动结束时,我想添加更多数据,所以我添加了willDisplay功能

func collectionView(_ collectionView: UICollectionView, 
numberOfItemsInSection section: Int) -> Int {

    return self.vitrinDecodePost.count
}

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {

    let lastindex = self.vitrinDecodePost.count - 1
    if indexPath.row == lastindex{

        loadDatas(limit: 20)
        self.collectionVitrin.reloadData() 


    }

}

当页面加载时,我的单元格中会显示10个项目,但当我到达页面末尾(最后一个索引)时,collectionview不会显示任何内容。它必须在my collectionview单元格中显示20项。我忘记了什么?

您应该删除
函数中在
加载数据(限制:20)
之后调用的
self.collectionsRn.reloadData()

但如果我能给你一个建议,在collectionview上实现无限滚动,我会做一些改变

首先,我建议您更改api调用。 您应该保持每个api调用返回的元素数量的限制,但也应该实现一个偏移量变量。这是更有效的

在您的情况下,您的第二个api调用只是再次请求相同的对象,请求中有更大的限制。您每次请求的数据基本相同。 添加偏移量使您每次只能请求新数据。此偏移量应为您已有的数据量

其次,当您到达数据末尾或已经请求数据时,您应该尝试添加故障保护机制。否则,如果到达集合视图的底部,则最终将循环调用。下面是我将如何基于您的代码实现无限加载

 @IBOutlet weak var collectionVitrin: UICollectionView!
 var limitPerCall: Int = 10
 var isLoadindNewData = false
 var shouldLoadMoreData = true

 var vitrinDecodePost = [VitrinDecode]() // Decodable

 func loadDatas(limit : Int, offset: Int) {

     guard let url = URL(string: "my Url") else { return }
     let session = URLSession.shared
     let request = NSMutableURLRequest(url: url as URL)
     request.httpMethod = "POST"
     let parameters = ["limit": "\(limit)", "offset": "\(offset)"] as Dictionary<String, String>
     guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
     request.httpBody = httpBody

     let task = session.dataTask(with: request as URLRequest) { [weak self]
         (data, response, error) in
         guard let strongSelf = self, let _:NSData = data as NSData? , let _:URLResponse = response, error == nil else {

            print("Mistake")
            return
        }

       /// No More data to gather stop making api calls
        guard let data = data else { 
           strongSelf.shouldLoadMoreData = false
           return 
        }
        do {

            let abc = try JSONDecoder().decode([VitrinDecode].self, from: data)
            strongSelf.vitrinDecodePost.append(contentsOf: abc)

            //// Reload the new data and and indicates that api call can be 
            made again
            DispatchQueue.main.async {
                strongSelf.isLoadingNewData = false
                strongSelf.collectionVitrin.reloadData()
            }

        } catch { print(error)}

}
task.resume()
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection 
    section: Int) -> Int {

    return self.vitrinDecodePost.count
}

func collectionView(_ collectionView: UICollectionView, willDisplay cell: 
    UICollectionViewCell, forItemAt indexPath: IndexPath) {

    let lastindex = self.vitrinDecodePost.count - 1
    if indexPath.row == lastindex && !isLoadindNewData && shouldLoadMoreData {
        /// Forbids multiple api calls to happen at the same time
        isLoadindNewData = true
        loadDatas(limit: limitPerCall, offset: vitrinDecodePost.count)
    }

}
@IBOutlet弱var CollectionsCrn:UICollectionView!
var limitPerCall:Int=10
var isLoadindNewData=false
var shouldLoadMoreData=true
var-cristendcodepost=[cristendcode]()//可解码
func加载数据(限制:Int,偏移量:Int){
guard let url=url(字符串:“我的url”)else{return}
让session=URLSession.shared
let request=NSMutableURLRequest(url:url作为url)
request.httpMethod=“POST”
让参数=[“限制”:“\(限制)”,“偏移量”:“\(偏移量)”]作为字典
guard let httpBody=try?JSONSerialization.data(带jsonObject:parameters,options:[])else{return}
request.httpBody=httpBody
让task=session.dataTask(其中:request作为URLRequest){[weak self]
(数据、响应、错误)
guard let strongSelf=self,let u3;:NSData=data as NSData?,let 3;:URLResponse=response,error==nil else{
打印(“错误”)
回来
}
///不再收集数据,停止api调用
保护let data=data else{
strongSelf.shouldLoadMoreData=false
回来
}
做{
让abc=try JSONDecoder().decode([CernDecode].self,from:data)
strongSelf.cristendcodepost.append(内容:abc)
////重新加载新数据并指示可以调用api
再次制造
DispatchQueue.main.async{
strongSelf.isLoadingNewData=false
strongSelf.CollectionsCrn.reloadData()
}
}捕获{打印(错误)}
}
task.resume()
}
func collectionView(collectionView:UICollectionView,numberOfItemsInSection
节:Int)->Int{
返回self.cristendcodepost.count
}
func collectionView(collectionView:UICollectionView,将显示单元格:
UICollectionViewCell,forItemAt indexPath:indexPath){
让lastindex=self.cristndeCodePost.count-1
如果indexath.row==lastindex&!IsLoadInNewData&&shouldLoadMoreData{
///禁止同时发生多个api调用
IsLoadInNewData=true
loadDatas(限制:limitPerCall,偏移量:CULTINDECODEPOST.count)
}
}
希望能有帮助


最好在do循环中设置一个断点,看看它的响应是否符合您的预期。您每次都在设置“self.cristendcodepost=abc”。您应该附加这些项目。请帮助我们获取更多代码。你能把你班确认的所有学员都发出去吗?更具体地说,对于
numberOfRowsInSection
未工作@cekisakurek.fetchDatas将是loaddatas我的错误我更新了@meggarI尝试了,但问题相同。Json对象即将出现,但Swift不再重新加载表。我看到了关于Pinterest布局的问题。谢谢你帮助我