首先,在表格视图的 cellForRowAt 方法中,为 UI 视图设置好初始状态,然后在需要进行动画的地方更改 UI 视图的状态,最后使用 UIView.animate 方法进行动画效果。如下所示:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
// 设置 UI 视图的初始状态
cell.uiView.alpha = 0
// 根据需要进行动画
if indexPath.row % 2 == 0 {
UIView.animate(withDuration: 0.5, delay: 0.1 * Double(indexPath.row), options: .curveEaseInOut, animations: {
cell.uiView.alpha = 1
}, completion: nil)
} else {
UIView.animate(withDuration: 0.5, delay: 0.1 * Double(indexPath.row), options: .curveEaseInOut, animations: {
cell.uiView.transform = CGAffineTransform(translationX: 0, y: -10)
}, completion: { _ in
UIView.animate(withDuration: 0.5, animations: {
cell.uiView.transform = .identity
cell.uiView.alpha = 1
})
})
}
return cell
}
在上面的代码示例中,我们首先为 UI 视图设置了一个初始的 alpha 值为 0,然后在需要进行动画的地方更改了 alpha 值或者进行了一些变换,比如将 UI 视图向上平移 10 点。最后使用 UIView.animate 方法进行动画,其中 delay 参数是根据行数来设置的,可以使得动画顺序更加合理。对于奇数行和偶数行,我们分别使用了不同的动画方式,以达到更好的效果。