【问题标题】:How can I animate any UIView inside UITableViewCell?如何为 UITableViewCell 中的任何 UIView 设置动画?
【发布时间】:2015-06-05 20:14:02
【问题描述】:
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 中的任何动画。我知道我无法为现有标签设置动画,因为它们有约束。

【问题讨论】:

    标签: uitableview animation tableviewcell


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      相关资源
      最近更新 更多