Faisal Al Saadi Faisal Al Saadi - 7 months ago 70
Swift Question

ios swift : How can i delay cell to appear in a tableview?

I have

uitableview
and I wanna make cells show one after one
that's gonna after number of seconds

I have tried
sleep(2)
and
dispatchafter
inside of
cellForRowAtIndexPath
method but neither works

I just want that returned cell to wait number of seconds.
Here's the code :

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! as! CustomCell

cell.chatText.text = self.texts[indexPath.row]
cell.textLabel?.textColor = UIColor.whiteColor()
cell.backgroundColor = UIColor.clearColor()
sleep(4)
return cell
}


Any idea ?

Answer

In Swift 2.1+, this should get you an animated insertion of a cell to your tableView. I'd put the dispatch_after in your viewDidAppear or viewDidLoad of your UITableViewController or UIViewController that contains the tableView.

let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
tableView.beginUpdates()
tableView.insertRowsAtIndexPaths([YourIndexPathYouWantToInsertTo], withRowAnimation: .Fade)
tableView.endUpdates()
}

And to create an NSIndexPath:

NSIndexPath(forRow: 0, inSection: 0)
Comments