首先,您应该将cell.addSubview(label)
移动到动画块的外部,并将该标签添加到单元的contentView
。
回到你的问题。你不能动画UILabel的背景颜色。尽管如此,你可以在UILabel后面使用相同大小的UIView。
要获得UIView的变色一旦它出现我用一个UITableViewCell子类:
class AnimatedCell : UITableViewCell {
let animatedView = UIView()
/* Setup by adding animatedView to the contentView and setting the
animated view's initial frame and colour.
*/
func animate() {
UIView.animateWithDuration(3.0) {
animatedView.backgroundColor = UIColor.redColor()
}
}
然后在你的UITableViewController
子类,提出了UITableView
将填充视图控制器时,因此你需要动画的细胞:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated: Bool)
for cell in tableView.visibleCells() as! [UITableViewCell] {
if let animatedCell = cell as? AnimatedCell {
animatedCell.animate()
}
}
}
然后,当您滚动出现细胞:
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if let animatedCell = cell as? AnimatedCell {
a.animateLabel()
}
}
此外,您可以使用AutoLayout进行动画制作,您需要更改要动画的NSLayoutConstraint
上的constant
。这给出了一个很好的例子:iOS: How does one animate to new autolayout constraint (height)