首页 > 解决方案 > 旋转关闭 tableview 扩展部分时不执行动画

问题描述

我已经构建了一个可扩展的 Tableview,我想要一个箭头,当单元格未展开时指向左侧,如果单元格展开则向下。

第一个动画(指向向下的箭头)就像一个魅力。当试图向后旋转时(同时关闭展开的单元格),它只是跳回到正常状态而没有任何动画。在我的 cellForRow 中,我这样做:

cell.image1.rotate(item.opened ? -.pi/2 : 0, duration: 0.4)

我有一个扩展:

extension UIView {
    func rotate(_ toValue: CGFloat, duration: CFTimeInterval) {
        let animation = CABasicAnimation(keyPath: "transform.rotation")
        animation.toValue = toValue
        animation.duration = duration
        animation.isRemovedOnCompletion = false
        animation.fillMode = CAMediaTimingFillMode.forwards
        self.layer.add(animation, forKey: nil)
    }
}

这个在 tableview 之外就像一个魅力。但是在 Tableview 内部,它总是在没有动画的情况下恢复正常。知道这是从哪里来的吗?

标签: iosswiftuitableviewanimation

解决方案


在方法中调用轮换action而不是func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

试试下面的代码。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let cell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell
    cell.rotateArrow()
}

在 CustomTableViewCell

class CustomTableViewCell: UITableViewCell {

    @IBOutlet weak var arrowImageView: UIImageView!

    var isOpened = false

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    func rotateArrow() {

        isOpened = !isOpened
        arrowImageView.rotate(isOpened ? -.pi/2 : 0, duration: 0.4)
    }
}

推荐阅读