重新加载数据时,UICollectionView不能平滑滚动

时间:2016-12-09 10:30:44

标签: ios swift swift2 uicollectionview

在我的UICollecitonView中,我使用

从API附加数据

self.DataTableCollectionView.reloadData()

但随着我的收藏中的数据越来越多,其滚动变得粗糙,加载一些页面后,向上或向下滚动变得非常困难。它被卡住了。

最终,当我尝试一次加载1000行时,滚动工作顺利,但是当我尝试使用API​​一次分页并加载50行时,就很难滚动。

任何人可以帮我解决问题是什么?

我无法弄清楚错误是什么? self.DataTableCollectionView.reloadData()对此负责吗?

以下是在scroll上加载数据的代码:

func scrollViewDidScroll(scrollView: UIScrollView) {

     let offsetY = scrollView.contentOffset.y
     let contentHeight = scrollView.contentSize.height

     if(offsetY > (contentHeight - scrollView.frame.size.height)){              

         let seconds = 3.0
         let delay = seconds * Double(NSEC_PER_SEC)
         let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))

         self.loadMoreData()
         dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
             self.DataTableCollectionView.reloadData()

         })                
      }        

}

==========

我正在重复使用单元格

self.DataTableCollectionView .registerNib(UINib(nibName: "DCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: dCellIdentifier)
self.DataTableCollectionView .registerNib(UINib(nibName: "CCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: cCellIdentifier) 

并重复使用:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

let dCell : DCollectionViewCell = collectionView .dequeueReusableCellWithReuseIdentifier(dCellIdentifier, forIndexPath: indexPath) as! DCollectionViewCell

let cCell : ContentCollectionViewCell = collectionView .dequeueReusableCellWithReuseIdentifier(cCellIdentifier, forIndexPath: indexPath) as! CCollectionViewCell       
}

======

添加更具体的代码:

现在我已经更新了滚动功能,

func scrollViewDidScroll(scrollView: UIScrollView) {
    let offsetY = scrollView.contentOffset.y
    let contentHeight = scrollView.contentSize.height
    if(offsetY > (contentHeight - scrollView.frame.size.height)){
       var returnTableData = NSMutableArray()

       self.InspectPageId = self.InspectPageId+1
       self.dataSource.populateData(PageId:self.InspectPageId)
       returnTableData = self.dataSource.DTableDataArray

       if(returnTableData.count>0){
          for i in 0..<returnTableData.count {
             self.TableDataArray.addObject(returnTableData[i])
          }
       }
       self.NumberOfRows = self.TableDataArray.count

       dispatch_async(dispatch_get_main_queue(),{
          self.DataTableCollectionView.reloadData()
       })
   }
}

以下是手动创建集合视图的代码:

if indexPath.row == 0 {
//Here Header Cell is creating
                let dateCell : DateCollectionViewCell = collectionView .dequeueReusableCellWithReuseIdentifier(dateCellIdentifier, forIndexPath: indexPath) as! DateCollectionViewCell
                dateCell.dateLabel.font = UIFont(name:"HelveticaNeue", size: 12)
                dateCell.dateLabel.textColor = UIColor.blackColor()
                dateCell.dateLabel.textAlignment = .Left
                dateCell.dateLabel.text = UMIDDataArray[rowIndex-1] as? String
                dateCell.backgroundColor = UIColor.whiteColor()
                dateCell.layer.shouldRasterize = true
                dateCell.layer.rasterizationScale = UIScreen.mainScreen().scale
                return dateCell
            } else {
//Here Data Cell is Creating
                let contentCell : ContentCollectionViewCell = collectionView .dequeueReusableCellWithReuseIdentifier(contentCellIdentifier, forIndexPath: indexPath) as! ContentCollectionViewCell
                contentCell.contentLabel.font = UIFont(name:"HelveticaNeue", size: 12)
                contentCell.contentLabel.textColor = UIColor.blackColor()
                contentCell.contentLabel.textAlignment = .Left
                contentCell.bottomBorder.hidden  = false
                contentCell.layer.shouldRasterize = true
                contentCell.layer.rasterizationScale = UIScreen.mainScreen().scale

                let LensData:NSArray =  TableDataArray[rowIndex-1] as! NSArray
                let ColumnValue = LensData[colIndex-1] as? String
                contentCell.contentLabel.text = ColumnValue
                contentCell.backgroundColor = UIColor.whiteColor()

                return contentCell
            }

Following is the code which is use to take data from API:

//function of DataSource Class.
func populateData(PageId:Int){
var returnData = NSMutableArray()
let OtherColobjects = NSMutableArray()

let Urlpath = SetApiUrl()
let url: NSURL = NSURL(string: Urlpath)!
let urlRequest = NSURLRequest(URL: url)

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)

let semaphore = dispatch_semaphore_create(0)
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) in

guard error == nil else {
return
}

guard let responseData = data else {
return
}

do {
guard let Data = try NSJSONSerialization.JSONObjectWithData(responseData, options: []) as? [String: AnyObject] else {
return
}

for anItem in Data["result"]!["DATA"] as! [Dictionary<String, AnyObject>] {
let d1 = self.checkForNull(anItem["data1"]!)
let d2 = self.checkForNull(anItem["data2"]!)
let d3 = self.checkForNull(anItem["data3"]!)
let d4 = self.checkForNull(anItem["data4"]!)
...... // Total 20 Columns

let obj = [ d1, d2, d3, d4,.............,d20 ]

OtherColobjects.addObject(obj)
}
dispatch_semaphore_signal(semaphore)
} catch {
return
}
}
task.resume()

dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
self.NumberOfRows = returnData[0].count
self.DTableDataArray = returnData[1] as! NSMutableArray
}

6 个答案:

答案 0 :(得分:1)

您应该在reloadData()上发送MainThread。根据苹果文档,操作UI应始终在MainThread中完成。

答案 1 :(得分:1)

如果self.loadMoreData()不是异步,则会阻止您的用户界面。 应在self.DataTableCollectionView.reloadData()的主要主题上调用self.loadMoreData()

即使没有阻止,您每页都会多次调用loadMoreData()次。 您应该添加一个布尔值来检查您是否已经加载数据,让我们称之为isLoading。 初始化viewcontroller时将isLoading设置为false。 在self.loadMoreData()中将其设置为true,并更改scrollViewDidScroll(scrollView: UIScrollView)中的签入,使其如下所示:

if(offsetY > (contentHeight - scrollView.frame.size.height)) && !isLoading{  
    self.loadMoreData()
}

答案 2 :(得分:1)

您应该只从主线程更新您的UI,所以改为这样做......

Swift 2.x

           dispatch_async(dispatch_get_main_queue()), {
                self.DataTableCollectionView.reloadData()
            }

Swift 3

DispatchQueue.main.async {
    self.DataTableCollectionView.reloadData()
}

如果这不能解决问题,那么您可能还需要在后台线程上调用loadMoreData() ...

Swift 2.x

        dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)){
             self.loadMoreData()
        }

Swift 3

DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
     self.loadMoreData()
}

目前尚不清楚您的代码是如何工作的,因为您尚未向我们展示您的loadMoreData()函数。实际上看起来你可能意味着从DataTableCollectionView.reloadData()内部调用loadMoreData,但是如果没有看到这个功能我就无法分辨。请添加其他代码

答案 3 :(得分:0)

在主队列中重新加载搭配

dispatch_async(dispatch_get_main_queue(),{
   self.DataTableCollectionView.reloadData()
}

答案 4 :(得分:0)

在您的出队单元格后添加以下2行

cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;

答案 5 :(得分:0)

尝试将reload collectionview从scrollviewdidscroll移动到loadmoredata()

func loadmoredata(){

/ *  1.列出项目  2.然后在最后调用realoadata  3.如果你有单元格中的图像,那么使用图像缓存,你可以编程图像缓存或使用像SDWebImage这样的库 * /

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),{self.DataTableCollectionView.reloadData()})

}