ios swift:如何延迟单元格出现在tableview中?

时间:2016-04-27 18:43:34

标签: ios swift uitableview

我有uitableview,我想让细胞一个接一个地显示出来  那将是几秒钟之后

我在sleep(2)方法中尝试了dispatchaftercellForRowAtIndexPath但是没有效果

我只想让返回的单元格等待秒数。 这是代码:

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
}

有什么想法吗?

3 个答案:

答案 0 :(得分:3)

在Swift 2.1+中,这应该可以让你在tableView中动画插入一个单元格。我将dispatch_after放在您的viewDidAppear或者包含tableView的UITableViewController或UIViewController的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)

答案 1 :(得分:2)

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
}

您必须为每个单元格设置越来越多的延迟以查看动画并逐个显示一个单元格

希望对你有帮助

答案 2 :(得分:1)

试试performSelector(selector:, withObject:, afterDelay:)。将该方法放在您的单元格函数中,并创建另一个函数(它将成为performSelector的选择器),您可以在其中显示单元格。从技术上讲,它应该工作(它应该延迟每个单元格返回)但我不能保证它会在你的情况下。试一试!