2016-01-24 149 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() 

    } 
相关问题