Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 733
Faisal Al Saadi Avatar asked Feb 08 '23 03:02

Faisal Al Saadi


2 Answers

In cellForRow method add this 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()

    let delay = 0.55 + Double(indexPath.row) * 0.5; //calculate delay
    print(delay) // print for sure

    UIView.animateWithDuration(0.2, delay: delay, options: .CurveEaseIn, animations: {
        cell.alpha = 1.0 // do animation after delay
    }, completion: nil)

    return cell
}

You have to set up more and more delay for each cell to see animation and display one cell after another

Hope it help you

like image 185
kamwysoc Avatar answered Feb 13 '23 05:02

kamwysoc


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)
like image 30
GhostBob Avatar answered Feb 13 '23 05:02

GhostBob