根据label.text更改TableViewCell高度?

时间:2016-01-24 21:31:49

标签: ios swift uitableview

如何更改单元格高度以使UILabel适合?我没有在我的项目中使用自动布局。

此外,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
    }

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

使用heightForRowAtIndexPath的上述注释在不使用自动布局时是可以接受的(尽管我强烈建议您使用它)。

使用此帖中描述的方法计算标签填充某个字符串时的高度:How to calculate UILabel height dynamically?

答案 1 :(得分:0)

1)您可以使用方法设置约束,您可以通过以下方式修改单元格的高度(自定义UITableViewCell中名为book_title的标签示例)

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)你必须在这些方法中调用这个方法:

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

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

        setupComponents()

    }
相关问题