Yury Alexandrov
Yury Alexandrov

Reputation: 2408

refreshing table while scrolling ios swift

I have tableView with custom cell. I load some information from the internet and add it to the table if user scroll table down. Problem: after loading information new cells sometimes rewrite old cells, and sometimes blank cells appears in this table while scrolling. There is my code:

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()
    }
}

example of blank screen

Upvotes: 0

Views: 1972

Answers (1)

0xRLA
0xRLA

Reputation: 3369

I got the same problem when I reused the cell variable as you do. Try to not put your cells in a list but instead save your result list as an instance variable and get the objects by in index in cellForRowAtIndexPath function as shown below.

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
}

Upvotes: 1

Related Questions