【问题标题】:Change TableViewCell height depending on label.text?根据 label.text 更改 UITableViewCell 高度?
【发布时间】:2016-09-02 16:14:17
【问题描述】:

如何更改单元格高度以使 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
    }

有什么想法吗?

【问题讨论】:

  • @originaluser2 问题是文本已经设置在那里,我的来自查询。
  • heightForRowAtIndexPathcellForRowAtIndexPath 之后被调用,那么问题出在哪里?只需计算 cellForRowAtIndexPath 中的文本大小并在 heightForRowAtIndexPath 中返回它们。
  • @originaluser2 怎么样?

标签: ios swift uitableview


【解决方案1】:

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

可以使用本文中描述的方法来计算标签在填充特定字符串时的高度:How to calculate UILabel height dynamically?

【讨论】:

  • 嗯,所以我在 ViewController.swift 顶部添加了代码,并将我的代码更改为:pastebin.com/MJxPV7JX - 但它根本没有改变大小..?跨度>
【解决方案2】:

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()

    }

【讨论】:

    猜你喜欢
    • 2012-04-07
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-01
    • 2011-08-06
    • 2013-06-15
    相关资源
    最近更新 更多