gpt4 book ai didi

ios - 将单元格的高度设置为等于标签内容

转载 作者:行者123 更新时间:2023-11-30 13:35:33 27 4
gpt4 key购买 nike

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

我首先设置约束

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

最佳答案

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

tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableViewAutomaticDimension

其中 44 应该是某种平均行高。那么您根本不必实现方法 estimatedRowHeightheightForRow...

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

// if cell is of kind textview cell
return UITableViewAutomaticDimension
// else
return some static value

关于ios - 将单元格的高度设置为等于标签内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36115068/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com