【问题标题】:refreshing table while scrolling ios swift滚动ios swift时刷新表格
【发布时间】:2014-08-26 08:34:03
【问题描述】:

我有带有自定义单元格的 tableView。如果用户向下滚动表格,我会从 Internet 加载一些信息并将其添加到表格中。问题:加载信息后新单元格有时会重写旧单元格,有时滚动时此表中会出现空白单元格。有我的代码:

var Bool canEdit = true
@IBOutlet var table : UITableView!
var eventList : [EventCell] = [] // EventCell - custom cell class

func addEventsAndRefresh() {
   if (canEdit){        
       canEdit = false
       HTTPManager.getEvents(isFuture: true, offset: eventList.count, didLoad: getEvents) //it creates url and call function "getEvents" after ending async request
   }    
}

func getEvents(response : NSURLResponse!, data : NSData!, error : NSError!) {
    if ((error) != nil) {
        HTTPManager.showErrorAlert()
    } else {
        var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSArray
        for elementOfArray in result {
            var cell : EventCell = table.dequeueReusableCellWithIdentifier("EventCell") as EventCell
            ... // parsing result to cell
            eventList.append(cell)
            
        }
        table.reloadData()
        canEdit = true
    }
}


func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
    return eventList.count
}

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
    return eventList[indexPath.row]
}

func scrollViewDidEndDragging(scrollView: UIScrollView!, willDecelerate decelerate: Bool) {
    var currentOffset = scrollView.contentOffset.y;
    var maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height;
    
    if (maximumOffset - currentOffset <= -40.0 && canEdit) {
        addEventsAndRefresh()
    }
}

【问题讨论】:

  • 对此不确定,但我的直觉是,虽然缓存表格单元格的想法很聪明,但这可能是导致问题的原因。无需缓存表格视图单元格,只需缓存 data 并根据需要在 tableView(tableView:, cellForRowAtIndexPath indexPath:) 中创建单元格(按照通常的单元格创建模式)。

标签: ios swift tableview


【解决方案1】:

当我像你一样重用单元格变量时遇到了同样的问题。 尽量不要将单元格放入列表中,而是将结果列表保存为实例变量,并通过 cellForRowAtIndexPath 函数中的索引获取对象,如下所示。

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
     var cell : EventCell = table.dequeueReusableCellWithIdentifier("EventCell") as EventCell
     var element = result[indexPath.row] as YourObject
     //Do something with cell
     return cell
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    相关资源
    最近更新 更多