2015-04-01 81 views
1
let label = UILabel(frame: CGRectMake(20.0, 20.0, 15.0, 15.0)) 
label.backgroundColor = UIColor.flamingoColor() 

UIView.animateWithDuration(3.0, animations: { 
    cell.addSubview(label) 
    label.backgroundColor = UIColor.yellowColor() 
}) 

我把这段代码放在tableView:cellForRowAtIndexPath: - >结果是一个有黄色背景的子视图,但我没有看到任何动画。同样是方法tableView:didEndDisplayingCell:如何在UITableViewCell中设置动画UIView?

我应该使用哪种方法,或者我应该放哪种动画来查看UITableViewCell中的任何动画。我知道我不能动画现有的标签,因为这些都是有约束力的。

回答

0

首先,您应该将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)