Ios 将动画应用于UIKit类的每个实例?

Ios 将动画应用于UIKit类的每个实例?,ios,swift,Ios,Swift,假设我有一些简单的tableview动画代码。有没有一种方法可以将此应用于我项目中的每个tableview?我当前的项目相当大,每个文件夹都有单独的VCs和故事板。有什么方法可以让我普遍应用更改吗 func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { //If transactionPage is set to -1, it'

假设我有一些简单的tableview动画代码。有没有一种方法可以将此应用于我项目中的每个tableview?我当前的项目相当大,每个文件夹都有单独的VCs和故事板。有什么方法可以让我普遍应用更改吗

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    //If transactionPage is set to -1, it's because we've reached the end of the transactions
    if transactionPage != -1 && indexPath.row == (tableData.rows(inSection: indexPath.section).count) - 1 {
        loadMoreTransactions()
    }

    if arrIndexPath.contains(indexPath) == false {
        cell.alpha = 0

        //Slide from bottom
        let transform = CATransform3DTranslate(CATransform3DIdentity, 0, 200, 
        0)

        cell.layer.transform = transform

        UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 1, 
            initialSpringVelocity: 1, options: .curveEaseOut, animations: {
            cell.alpha = 1
            cell.layer.transform = CATransform3DIdentity
        })

        arrIndexPath.append(indexPath)
    }
}
协议 第一种可能的解决方案是创建协议。创建协议,然后扩展它并声明用于设置单元格动画的方法

protocol CellAnimating where Self: UITableViewDelegate {}

extension CellAnimating {

    func animateCell(_ cell: UITableViewCell) {
        cell.alpha = 0

        let transform = CATransform3DTranslate(CATransform3DIdentity, 0, 200, 0)

        cell.layer.transform = transform

        UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
            cell.alpha = 1
            cell.layer.transform = CATransform3DIdentity
        })
    }

}
然后,若要查看要使用此方法的控制器,只需实现此协议,并且在
内部将显示
调用此方法

class ViewController: UIViewController, UITableViewDelegate {
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        ...
        animateCell(cell)
        ...
    }
}

extension ViewController: CellAnimating {}
子类化视图控制器 我想到的第二个选项是,您可以创建
UIViewController
的子类,并在这里声明委托方法
willDisplay

class ViewController: UIViewController, UITableViewDelegate {
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        ...
    }
}

然后,只需将每个要使用它的视图控制器设置为
ViewController

的子类,谢谢您的回答!我一直在尝试实现第2个,但您能否进一步详细解释一下它是如何工作的?我的所有表视图当前都已从自定义表视图类继承。如果我在类定义中添加了动画代码,并在其他一些VCs中调用了willDisplay函数,但动画不起作用…@teachMeSenpai look,您有一些视图控制器,比如说
MyVC
。该视图控制器必须继承自
ViewController
,然后当
将显示
方法应在
MyVC
中调用时,将调用该方法。所以:
类MyVC:ViewController
。这就是你想要的吗?