2014-09-29 50 views
1

我有一個UITableView,它還包含也包含UITableViews的自定義單元格。我在獲取這些細胞的高度時遇到了問題。包含UITableView(iOS8和AutoLayout)的UITableViewCell的高度

我得到heightForRowAtIndexPath中的高度,並做到這一點,我填充子tableView(單元格內)並調用layoutIfNeeded。這給了我這個tableView的正確contentSize。問題是單元格的整體大小是錯誤的,不會改變。所以調用cell.bounds.height返回一個不正確的值。

 let cell:GroupCell = tableView.dequeueReusableCellWithIdentifier("GroupCell") as GroupCell 
     cell.configure(field as SingleField, delegate: self) // populates data 
     cell.tableView.layoutIfNeeded() 
     // cell.tableView.contentSize is correct 
     return cell.bounds.height // is wrong - bounds haven't changed 

Cell Autolayout

任何人都可以點我在正確的方向?順便說一句 - 我只針對iOS8。

回答

0

嘗試創建UITableViewCell的子類,添加TableView委託給它,像往常一樣使用它。

+0

梅德感謝,我的自定義單元格已經這樣做了。問題是父UITableView無法獲得這個單元格的正確大小。 – 2014-09-29 09:36:00

0

我認爲問題出在UITableView中。你悲傷的表格有正確的內容大小,但它有不正確的大小。計算正確的內容大小後,您應該手動更改tableView高度。我認爲它會幫助你。提示:您可以觀察contentSize屬性,每次更改時都可以調整表格視圖的大小。要做到這一點 - 將高度約束添加到低優先級(例如750)的表格中,而不是在需要時更改它。在這種情況下,您的表格將同時具有內容大小和self.frame.heigh。

+0

謝謝塞利弗,有趣的角度。我可以計算標籤的大小,邊距等,並將它們添加到tableview內容大小。我希望自動佈局約束會自動發生。 – 2014-09-29 09:38:05

0

我設法解決這個如下:

  1. 我把高度約束(大於或等於)上的UITableView(細胞內)。我的這個優先級設置爲高
  2. 我下邊距的優先級設置爲低
  3. 在配置我的自定義單元格我打電話setNeedsUpdateConstraints(),它可以通過消除其無效的高度約束,然後從重新計算它在將其添加回來之前,表視圖的內容大小。
  4. 最後,在heightForRowAtIndexPath cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height現在返回正確的高度

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
    
        let field = fields[indexPath.row] 
    
        let cell:GroupCell = tableView.dequeueReusableCellWithIdentifier("GroupCell") as GroupCell 
        cell.configure(field as SingleField, delegate: self) 
        return cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height 
    } 
    
    func configure(field:SingleField,delegate:GroupDelegate){ 
    
        self.field = field 
        self.delegate = delegate 
        nameLabel.text = field.name 
        tableView.reloadData() 
        setNeedsUpdateConstraints() 
    } 
    
    
    override func updateConstraints() { 
        tableView.removeConstraint(tableViewHeightConstraint) 
        tableViewHeightConstraint = NSLayoutConstraint(item: tableView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: tableView.contentSize.height) 
        tableView.addConstraint(tableViewHeightConstraint) 
        super.updateConstraints() 
    } 
    
相關問題