UIView 动画在 UITableViewCell 中无法正常工作

UIView animation doesn't work properly inside UITableViewCell

我有一个 UITableViewCell,它包含一个 UIView,在调用 TableViewCell 的 awakeFromNib() 时正在动画化。 动画确实适用于 TableViewController 出现时调用的单元格,但滚动时生成的单元格根本不移动。 我该如何解决这个问题? I added an example on Github to demonstrate the issue.

TableViewController

import UIKit

class ViewController: UITableViewController {

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 20
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! TableViewCell

    return cell
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

TableViewCell

import UIKit

class TableViewCell: UITableViewCell {

@IBOutlet weak var animatorCell: UIView!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
    UIView.animateWithDuration(0.3, delay: 0.0, options: [.CurveEaseInOut, .Repeat, .Autoreverse], animations: { () -> Void in
        self.animatorCell.transform = CGAffineTransformMakeTranslation(0, 10)
        }, completion: nil)
}

}

我不确定,但由于您使用的是 dequeueReusableCell,我想 awakeFromNib 没有被调用。第一个单元格使用 awakeFromNib 初始化,但接下来的单元格将是相同的单元格,重新使用,因此它们不会使用 awakeFromNib 初始化。如果我错了,并且 awakeFromNib 调用下一个单元格,那么我猜你的动画在进入屏幕之前就已经完成了。

无论哪种方式,您都可以尝试在 tableView 中使用 tableView(_:willDisplayCell:forRowAtIndexPath:)(here) 之类的东西,然后从那里在单元格上调用动画方法。