2016-08-16 81 views
0

我想增加我的UITableviewCell高度取決於TableViewCell上的UILabel內容按鈕單擊。 我有搜索,但我找到約束的答案。swift:增加TableViewCell高度取決於UILabel而不使用約束

我想在不使用'Constarints'/ Autolayout的情況下動態增加UITabelViewCell高度。

我用下面的代碼獲取標籤身高:

func getLabelHeight(lbl : UILabel) -> CGFloat 
    { 
     let constraint = CGSizeMake(lbl.frame.size.width, CGFloat.max) 
     var size = CGSize() 

     let context = NSStringDrawingContext(); 

     let boundingBox : CGSize 

     boundingBox = NSString(string: lbl.text!).boundingRectWithSize(constraint, 
                    options: NSStringDrawingOptions.UsesLineFragmentOrigin, 
                    attributes: [NSFontAttributeName: self], 
                    context: context).size 

     size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height)) 
     return size.height; 
    } 

,但我不能在UITableView中使用此代碼。爲了提高TableViewCell高度我已經寫了下面的代碼:

func btnReadMoreClick(sender: UIButton){ 
     let buttonTag = sender.tag 

     indexOfReadMoreButton = sender.tag 
     isReadMoreButtonTouched = true 

     tableVDetail.beginUpdates() 
     tableVDetail.reloadRowsAtIndexPaths([NSIndexPath(forItem: indexOfReadMoreButton, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic) 
     tableVDetail.endUpdates() 
    } 

,並設置單元格的高度在

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat 

但是使用這個我不能讓我的輸出。 :(

提前感謝!

+0

如果你真的想這樣做,使這個函數來計算高度靜態和直接傳入文本進行綁定,所以你可以輕鬆地調用CellName.getLabelHeight ...在heightForRowAtIndex .... – mbutan

+0

@mbutan你可以解釋一下我使用代碼。或者如果你有另一種方式,那麼也請告訴他們。 –

回答

0

如果你設置你的正確的約束,它應該做的工作休息。

這只是一個輔助自動調整你的細胞,並計算出預期的高度。

extension UITableViewCell { 
    func calcualteHeight(inTableview tableview: UITableView) -> CGFloat { 
     self.setNeedsUpdateConstraints() 
     self.updateConstraintsIfNeeded() 
     self.bounds = CGRectMake(0, 0, CGRectGetWidth(UIScreen.mainScreen().bounds), CGRectGetHeight(self.bounds)) 
     self.setNeedsLayout() 
     self.layoutIfNeeded() 

     let height = self.contentView.systemLayoutSizeFittingSize(self.bounds.size, withHorizontalFittingPriority: UILayoutPriorityFittingSizeLevel, verticalFittingPriority: UILayoutPriorityFittingSizeLevel).height 
     return height 
    } 
} 

在委託的TableView,獲取您的計算單元和填充數據。

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
     let cell = tableView.dequeueReusableCellWithIdentifier(self.viewModel.reuseIdentifier(atIndexPath: indexPath)) as! YourCell 
     cell.setupData(fillCellYourData) 
     return cell.calcualteHeight(inTableview: tableView) 
} 
+0

我在沒有使用單元格約束的情況下執行此操作 –

相關問題