2016-01-20 50 views
1

我遇到了一個問題,我通過調整自動佈局約束來設置表格單元格中簡單UIView的大小。UITableViewCell中的約束動畫啓動不正確

當我第一次啓動表格時,一切都被打破了。

enter image description here

如果我重新加載表,它精美的作品。

enter image description here

它只有幾行代碼的單一視圖控制器。請下載這個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只是紅色視圖的父視圖,只是代表所述條可能的最大尺寸。

+0

事情是'cell.viewBarArea.frame.width'給細胞的原始寬度......就像如果你使用wAnyhAny和你的寬度是580比第一次給出580的寬度....你必須使用'viewWillLayoutSubviews'獲取更新的寬度,因爲每個設備 –

+0

因此,在viewWIllLayoutSubviews中,我應該遍歷我的可見表格單元格並應用動畫?這可能有效,但似乎有點密集。我會看看 –

+0

@El Captain,我剛剛意識到這是行不通的,因爲當他們滾動或做任何其他事情時,動畫會一次又一次地不停地運行。 –

回答

3

使用這條線的cellForRowAtIndexPath完蛋了

let cell = tableView.dequeueReusableCellWithIdentifier("TableCell", forIndexPath: indexPath) as! TableCell 
+0

該代碼有什麼問題? –

+0

這是常見的錯誤。別擔心。閱讀此http://stackoverflow.com/questions/25826383/when-to-use-dequeuereusablecellwithidentifier-vs-dequeuereusablecellwithidentifi或https://developer.apple.com/videos/play/wwdc2012-200/ – vaibby

+1

Omg這正是什麼我需要!你搖滾! –