ios swift:如何延迟单元格出现在表视图中



我有uitableview,我想让单元格一个接一个地显示这将在几秒钟后

我在cellForRowAtIndexPath方法中尝试过sleep(2)dispatchafter,但都不适用于

我只想让返回的手机等待几秒钟。这是代码:

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
}

知道吗?

cellForRow方法中添加以下代码:

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
}

你必须为每个单元格设置越来越多的延迟,才能看到动画并显示一个又一个单元格的

希望它能帮助你

在Swift 2.1+中,这将为您在tableView中动画插入一个单元格。我会把dispatch_after放在UITableViewController或包含tableView的UIViewController的viewDidPappear或viewDidLoad中。

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

创建NSIndexPath:

NSIndexPath(forRow: 0, inSection: 0)

尝试performSelector(selector:, withObject:, afterDelay:)。将方法放入单元格函数中,然后创建另一个函数(它将成为performSelector的选择器),在其中显示单元格。从技术上讲,它应该有效(它应该会延迟每个细胞的返回),但我不能保证在你的情况下会这样。试试看!

最新更新