UITableViewCell中的约束动画启动不正确
我遇到了一个问题,我通过调整自动布局约束来设置表格单元格中简单UIView的大小。UITableViewCell中的约束动画启动不正确
当我第一次启动表格时,一切都被打破了。
如果我重新加载表,它精美的作品。
它只有几行代码的单一视图控制器。请下载这个demo project看看它的行动。
下面是我的整个的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只是红色视图的父视图,只是代表所述条可能的最大尺寸。
使用这条线的cellForRowAtIndexPath完蛋了
let cell = tableView.dequeueReusableCellWithIdentifier("TableCell", forIndexPath: indexPath) as! TableCell
该代码有什么问题? –
这是常见的错误。别担心。阅读此http://stackoverflow.com/questions/25826383/when-to-use-dequeuereusablecellwithidentifier-vs-dequeuereusablecellwithidentifi或https://developer.apple.com/videos/play/wwdc2012-200/ – vaibby
Omg这正是什么我需要!你摇滚! –
事情是'cell.viewBarArea.frame.width'给细胞的原始宽度......就像如果你使用wAnyhAny和你的宽度是580比第一次给出580的宽度....你必须使用'viewWillLayoutSubviews'获取更新的宽度,因为每个设备 –
因此,在viewWIllLayoutSubviews中,我应该遍历我的可见表格单元格并应用动画?这可能有效,但似乎有点密集。我会看看 –
@El Captain,我刚刚意识到这是行不通的,因为当他们滚动或做任何其他事情时,动画会一次又一次地不停地运行。 –