2016-01-24 77 views
0

如何更改單元格高度以使UILabel適合?我沒有在我的項目中使用自動佈局。根據label.text更改TableViewCell高度?

另外,TableViewCell文本在cellForRowAtIndexPath中設置。

代碼:

var commentsArray: [String] = [] 

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

     let cell:TableViewCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell; 

     if self.commentsArray.count > indexPath.row{ 
      cell.commentsText.text = commentsArray[commentsArray.count - 1 - indexPath.row] 
      cell.commentsText.font = UIFont.systemFontOfSize(15.0) 
     } 

     return cell 
    } 

任何想法?

+0

看看http://stackoverflow.com/questions/19215199/dynamically-size-uitableviewcell-according-to-uilabel-with-paragraph-spacing – Hamish

+0

@ originaluser2問題是文本已經在那裏設置,我的是來自查詢。 –

+0

'heightForRowAtIndexPath'在'cellForRowAtIndexPath'後被調用,那麼問題是什麼?只需在'cellForRowAtIndexPath'中計算文本大小並將其返回到'heightForRowAtIndexPath'。 – Hamish

回答

0

以上使用heightForRowAtIndexPath的註釋在不使用自動佈局時是可以接受的(儘管我強烈推薦使用它)。

計算時,它具有一定的字符串填充可以用在這篇文章中描述的方法來完成標籤的高度:How to calculate UILabel height dynamically?

+0

嗯,所以我在ViewController.swift的頂部添加了代碼,並將我的代碼更改爲:pastebin.com/MJxPV7JX - 但它根本不會改變大小..? –

+0

你好?有任何想法嗎? –

0

1)您可以使用一種方法來設置約束,你可以修改在這種方式的小區的高度(實施例與被叫BOOK_TITLE在自定義的UITableViewCell標籤)

fune setupComponents(){ 

self.addSubview(book_title) 

book_title.topAnchor.constraintEqualToAnchor(self.topAnchor, constant: 5).active = true 
     book_title.leftAnchor.constraintEqualToAnchor(self.leftAnchor, constant: 10).active = true 
     book_title.rightAnchor.constraintEqualToAnchor(self.rightAnchor).active = true 
     book_title.widthAnchor.constraintEqualToAnchor(self.widthAnchor, constant: -20).active = true 
     book_title.heightAnchor.constraintEqualToConstant(90).active = true 
     book_title.numberOfLines = 0 
     book_title.lineBreakMode = NSLineBreakMode.ByWordWrapping 

} 

2)喲u必須調用這些裏面這個方法:

required init(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder)! 
     setupComponents() 
    } 

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) { 
     super.init(style: .Subtitle, reuseIdentifier: "CellId") 

     setupComponents() 

    } 
相關問題