如何在编辑时为UITableViewCell制作动画?

时间:2017-09-01 21:10:26

标签: ios swift uitableview animation

当用户点击表格视图的编辑按钮时,如何为表格视图单元格中的颜色更改设置动画?

点击编辑按钮时,Apple的动画会将所有单元格的内容向右移动,以在每个单元格中显示删除或插入按钮。我想添加与Apple同时发生的动画。我设法为单元格布局设置了动画,但没有设置颜色变化。

这就是我正在做的事情:

override func willTransition(to state: UITableViewCellStateMask) {
    super.willTransition(to: state)

    let willEdit = state.contains(.showingEditControlMask)

    toDateDaysLayoutConstraint.constant = willEdit ? 5.0 : 25.0
    daysNightsLayoutConstraint.constant = willEdit ? 5.0 : 10.0

    toDateTextView.textColor = willEdit ? UIColor.red : UIColor.darkText
    daysLabel.backgroundColor = willEdit ? UIColor.cyan : UIColor.clear        
}

要清楚,上面的layoutConstraint正确地更改了动画,但颜色在没有动画的情况下瞬间改变。

我还尝试使用UIView块动画设置颜色动画,如下所示:

    UIView.animate(withDuration: 5.0) { 
        self.toDateTextView.textColor = willEdit ? UIColor.red : UIColor.darkText
        self.daysLabel.backgroundColor = willEdit ? UIColor.cyan : UIColor.clear
    }

但是,我永远无法将颜色变为动画。我已尝试将上述代码放入willTransition(to state:)setEditing(_ editing: animated:),甚至是layoutSubviews()。我也在表控制器方法中尝试过它。但是,没有任何作用。

更新

到目前为止,我还尝试在CATransaction.begin()CATransaction.commit()之间包装所有内容,同时仅使用图层动画,甚至在调用后将commit放入didTransitionsuper。什么都行不通。

我想知道,是否有可能与苹果公司同时进行任何不是布局动画的动画?

1 个答案:

答案 0 :(得分:1)

根据我的理解,你只能为UIView的“动画”属性设置动画(参见this list)。 textColor不在其中。我已经使用了UIView.transition(with:duration:options:animations),文本颜色正确地“动画”了:

override func willTransition(to state: UITableViewCellStateMask) {

    super.willTransition(to: state)

    UIView.transition(with: textLabel!, duration: 5.0, options: .transitionCrossDissolve, animations: {
        self.textLabel?.textColor = state.rawValue == 1 ? UIColor.red : UIColor.black
    })
}

编辑1

根据您的评论,我设法重现了这个问题。我通过覆盖UILabel而不是didTransition(to:)来修复willTransition(to:)。所以我们先等待视图调整大小(因为出现了删除按钮),然后我们动画。但是,对于UITextView,这不起作用,除非您确保它具有固定的大小。

class TableViewCell: UITableViewCell {

    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var label: UILabel!

    override func didTransition(to state: UITableViewCellStateMask) {

        super.didTransition(to: state)

        UIView.transition(with: textView, duration: 3, options: .transitionCrossDissolve, animations: {
            self.textView.textColor = state.rawValue == 1 ? UIColor.red : UIColor.black
        })

        UIView.transition(with: label, duration: 3, options: .transitionCrossDissolve, animations: {
            self.label.backgroundColor = state.rawValue == 1 ? UIColor.red : UIColor.white
        })
    }
}

编辑2

如果您需要文本视图可调整大小,请异步执行动画:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    UIView.transition(with: self.textView, duration: 3, options: .transitionCrossDissolve, animations: {
        self.textView.textColor = state.rawValue == 1 ? UIColor.red : UIColor.black
    })
}

顺便说一下,我也尝试将UITextView子类化并覆盖layoutSubviews,但它不起作用......