简体   繁体   中英

UIView animation doesn't work properly inside UITableViewCell

I have a UITableViewCell, which contains a UIView that is being animated when the TableViewCell's awakeFromNib() is being called. The animation does work for cells that are called when the TableViewController appears but the cells that are being generated when scrolling don't move at all. How can I solve this? I added an example on Github to demonstrate the issue.

The 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.
}


}

The 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)
}

}

I'm not sure, but since you are using dequeueReusableCell , I guess awakeFromNib isn't called. The first cells are initialized using awakeFromNib , but the next cells will be the same cells, re-used, so they won't be initialized using awakeFromNib . If I'm wrong, and awakeFromNib is called for the next cells, then I guess your animation is finished before it enters the screen.

Either way, you could try to use something like tableView(_:willDisplayCell:forRowAtIndexPath:) ( here ) in your tableView, and and call an animation-method on the cell from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM