首页 > 解决方案 > UITableViewCell 动画被击中或错过。有时表格数据/单元格会在没有动画的情况下弹出

问题描述

所以我使用自定义动画来显示表格单元格的显示方式。它们有点淡入并向上滑动一点。我正在使用来自 API 调用的数据填充表。

我注意到的是,它并不总是发生。有时它按预期工作,有时单元格/数据只是突然出现,没有动画/运动。他们只是在动画结束时突然出现。我真的没有看到任何一致的模式在它何时起作用和何时不起作用。看起来很随意。

知道是什么导致了这种行为吗?

这是动画的代码以及它在 tableview 函数中的位置:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    var cell: RecentActivityCell = recentActivityView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! RecentActivityCell
    
    var lastInitialDisplayableCell = false

        //change flag as soon as last displayable cell is being loaded (which will mean table has initially loaded)
    if userActivityArray.count > 0 && !finishedLoadingInitialTableCells {
            if let indexPathsForVisibleRows = tableView.indexPathsForVisibleRows,
                let lastIndexPath = indexPathsForVisibleRows.last, lastIndexPath.row == indexPath.row {
                lastInitialDisplayableCell = true
            }
        }

        if !finishedLoadingInitialTableCells {

            if lastInitialDisplayableCell {
                finishedLoadingInitialTableCells = true
            }

            //animates the cell as it is being displayed for the first time
            cell.transform = CGAffineTransform(translationX: 0, y: 40/2)
            cell.alpha = 0

            UIView.animate(withDuration: 0.5, delay: 0.05*Double(indexPath.row), options: [.curveEaseInOut], animations: {
                cell.transform = CGAffineTransform(translationX: 0, y: 0)
                cell.alpha = 1
            }, completion: nil)
        }
    
    cell.backgroundColor = UIColor.clear
    
    if userActivityArray[indexPath.row].status == "Success" {
        cell.statusImage.image = UIImage(named: "passImage")
    } else {
        cell.statusImage.image = UIImage(named: "failImage")
    }
    
    cell.activity = userActivityArray[indexPath.row]
    return cell
}

标签: iosuitableview

解决方案


尝试通过覆盖在“yourTableViewCell”中使用您的动画:

override func prepareForReuse() {
        super.prepareForReuse()
        \\ Animation code over here
    }

不要在“CellForRowAt”中使用


推荐阅读