2015-07-13 70 views
1

我試圖在UITableView中使用自動佈局製作變量高度單元格。表格視圖單元格有兩個標籤:標題標籤和說明標籤。UITableView中的變量高度單元格僅在單元格不在視圖中時起作用

var viewBindingsDict: NSMutableDictionary = NSMutableDictionary() 
viewBindingsDict.setValue(myTitleLabel, forKey: "label") 
viewBindingsDict.setValue(myDescriptionLabel, forKey: "description") 
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[label]-10-|", options: nil, metrics: nil, views: viewBindingsDict as [NSObject : AnyObject]) as [AnyObject] 
let horizontalConstraints2 = NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[description]-10-|", options: nil, metrics: nil, views: viewBindingsDict as [NSObject : AnyObject]) as [AnyObject] 
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-10-[label]-5-[description]-10-|", options: nil, metrics: nil, views: viewBindingsDict as [NSObject : AnyObject]) as [AnyObject] 
self.contentView.addConstraints(horizontalConstraints + horizontalConstraints2 + verticalConstraints) 

並在表視圖控制器,

self.tableView.estimatedRowHeight = 60 
self.tableView.rowHeight = UITableViewAutomaticDimension 

在表視圖的數據源,

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

    // setup cell 

    cell.setNeedsUpdateConstraints() 
    cell.updateConstraintsIfNeeded() 
    return cell 
} 

這適用於大多數細胞,但總有一些不正確奠定一個或兩個細胞出。例如,在此test project中,第一行未正確排列,但當我滾動到底部(視圖的第一行)時,向上滾動,它自行修復。我嘗試使用兩個XIB並以編程方式創建單元格。但沒有運氣。

任何想法?請參閱test project以查看這種奇怪的行爲。

+0

嘗試不使用'self.tableView.estimatedRowHeight' – nathanwhy

+0

我在github中試過了你的代碼,它按預期工作。什麼是您的模擬器運行的Swift版本和iOS版本? – ozgur

+0

在模擬器中啓動您的應用程序,然後嘗試位於Xcode底部的「Debug View Hierarchy」選項。 – Krishna

回答

0

顯然,問題的真正根源是單元的框架的寬度直到它被顯示在屏幕上才被正確設置,即MyCell始終以320點框架寬度啓動。由於表格視圖會在顯示單元格之前計算行的高度,因此在iPhone 6或6以及寬度不是320點的情況下運行應用程序時,會導致出現問題。所以我在MyCell類的setupSubviews函數的開頭處添加了以下代碼。

self.frame.size.width = UIScreen.mainScreen().applicationFrame.size.width 

現在,只要顯示錶格視圖,單元格就會以正確的高度顯示。

而且爲了使用XIB時來解決這個問題,我重寫awakeFromNib

override func awakeFromNib() { 
    super.awakeFromNib() 
    // we need to set the cell's width so that content view's width will be set correctly 
    self.frame.size.width = UIScreen.mainScreen().applicationFrame.size.width 
} 

我已經更新了test project如果任何人的興趣。

相關問題