Faisal Al Saadi
Faisal Al Saadi

Reputation: 125

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 ?

Upvotes: 4

Views: 2148

Answers (3)

kamwysoc
kamwysoc

Reputation: 6859

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

Upvotes: 4

GhostBob
GhostBob

Reputation: 61

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)

Upvotes: 3

Lawrence413
Lawrence413

Reputation: 2016

Try performSelector(selector:, withObject:, afterDelay:). Put the method in your cell function and create another function (which is going to be the selector for performSelector) where you show the cells. Technically it should work (it should delay each cell return) but I can't guarantee that it will in your case. Give it a try!

Upvotes: 1

Related Questions