问题
I am running into an issue where I animate the size of a simple UIView in a table cell by adjusting an autolayout constraint.
When I launch the table for the first time, everything is broken.
If I reload the table, it works beautifully.
It's a single view controller with only a few lines of code. Please download this demo project to see it in action.
Here's my code in my whole UIViewController:
import UIKit
class TableCell: UITableViewCell {
@IBOutlet weak var constraintRedBarWidth: NSLayoutConstraint!
@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var viewBarArea: UIView!
@IBOutlet weak var viewRedBar: UIView!
}
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var tableData : [CGFloat] = [1, 0.90, 0.70, 0.80,0.50] //percentages
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func btnReloadTable(sender: AnyObject) {
tableView.reloadData()
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TableCell") as! TableCell
cell.labelTitle.text = "Item \(indexPath.row + 1)"
cell.constraintRedBarWidth.constant = 1
cell.layoutIfNeeded()
cell.constraintRedBarWidth.constant = cell.viewBarArea.frame.width * tableData[indexPath.row]
UIView.animateWithDuration(0.5, animations: {
cell.layoutIfNeeded()
})
return cell
}
}
viewBarArea is just the parent view of the red view and simply represents the possible max size of the bar.
回答1:
use this line cellForRowAtIndexPath thats it
let cell = tableView.dequeueReusableCellWithIdentifier("TableCell", forIndexPath: indexPath) as! TableCell
来源:https://stackoverflow.com/questions/34892039/animation-with-constraints-in-uitableviewcell-launches-incorrectly