【问题标题】:Swift iOS auto adjust height for UILabel for UITableViewCell()Swift iOS 为 UITableViewCell() 自动调整 UILabel 的高度
【发布时间】:2016-08-19 17:26:15
【问题描述】:

如何让它根据 textLabel 的长度自动调整每个单元格的高度?理想情况下,我希望 textLabel 也被包装,因此 textLabel 可以采用它需要的任意多行。以下代码是我目前拥有的:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let notification = self.fetchedTweetsArray[indexPath.row]

        let cell = UITableViewCell()
        cell.textLabel?.text = notification
        return cell
    }

【问题讨论】:

  • 你在使用自动布局吗?
  • 不使用自动布局

标签: ios iphone swift uitableview uilabel


【解决方案1】:

首先你的 cellForRowAtIndex 应该是这样的

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
     let cell : CustomCell! = tableView.dequeueReusableCellWithIdentifier("ID_CustomCell", forIndexPath: indexPath)  as! CustomCell

cell.selectionStyle =  UITableViewCellSelectionStyle.None

cell.lblData.text = "CustomCell....."
return cell

}

UILabel 的行数应为零。

现在根据 UILabel 的高度,您必须计算每个单元格的动态高度并将其保存在可变数组中,以便稍后您可以在 heightForRowAtIndex 中使用。

确保在 UILabel 上像这样自动调整大小

刚刚做了一个示例代码,大家可以下载观察。

Download sample code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-03
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多