设置单元格的高度等于标签内容

时间:2016-03-20 14:38:42

标签: ios swift uitableview

我有一个带有几个customCell的tableView,因此我无法使用estimatedRowHeight。但是在这个单元格中,我需要将行高设置为等于单元格内标签的内容。但它似乎没有显示所有文本。

我已经开始设置cosntraints

enter image description here

然后在单元子类中设置字体高度

descLabel!.font = UIFont.systemFontOfSize(14)

然后我创建计算功能

func calculateHeightForString(inString:String) -> CGFloat
{
    let messageString = inString
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = 2
    let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(14.0)]

    let attrString:NSMutableAttributedString? = NSMutableAttributedString(string: messageString, attributes: attributes)
    attrString!.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrString!.length))
    let rect:CGRect = attrString!.boundingRectWithSize(CGSizeMake(self.view.frame.width-24,CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, context:nil )//hear u will get nearer height not the exact value
    let requredSize:CGRect = rect


    return requredSize.height  //to include button's in your tableview

}

设置第1部分的高度

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

    if indexPath.section == 0 {

        return 160.0/320.0 * tableView.bounds.width
    } else if indexPath.section == 1 {
        return self.calculateHeightForString("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also th") + 24
    } else {
        return 100
    }
}

没有显示所有内容的结果

enter image description here

2 个答案:

答案 0 :(得分:0)

如果您已正确设置约束并且应用的部署目标为> = iOS 8,则可以使用自动行高计算。因此,您必须在img中执行以下操作:

viewDidLoad

其中 44 应该是某种平均行高。那么你根本不必实现方法tableView.estimatedRowHeight = 44 tableView.rowHeight = UITableViewAutomaticDimension estimatedRowHeight ......

您还可以实施heightForRow并执行以下操作:

heightForRow

答案 1 :(得分:0)

从你的String看起来缺少最后一行。这可能是由于底部的负面约束(在附图中显示为-4)。尝试将其改为积极的东西。

相关问题