编辑编辑:我从零开始在一个新项目中。每个故事板插座都是相同的,VC代码也是如此。它很有意思。
编辑:大家好,我放弃了。每个答案都开始成为主题的变体,而这个主题并没有解决这个问题。谢谢你的尝试。在ViewDidLoad
中,我设置了:
tableView.estimatedRowHeight = 85.0
,tableView.rowHeight = UITableViewAutomaticDimension
要换行的标签,标签行为0
然而,标签文本仍在其单元格中溢出。 完整的字符串是:“你好?如果我写一个长篇大论会发生什么?”
任何提示?
推荐功能后: enter image description here 结果: enter image description here
答案 0 :(得分:2)
您没有设置heightForRowAt indexPath .. 为此,您应该首先获得文本的大小 在我的情况下,我通过
获得了大小func rectForText(text: String, font: UIFont, maxSize: CGSize) -> CGSize
{
let attrString = NSAttributedString.init(string: text, attributes: [NSAttributedStringKey.font:font])
let rect = attrString.boundingRect(with: maxSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil)
let size = CGSize(width: rect.size.width, height: rect.size.height)//(, )
return size
}
并根据您的文字设置单元格的高度,在我的情况下
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
var totalHeight : CGFloat = 0
let str = yourString
let size : CGSize = rectForText(text: str, font:UIFont.boldSystemFont(ofSize: 15.0) , maxSize : CGSize(width: 200 * (SCREEN_WIDTH / 320), height: 20000) )
totalHeight = size.height
return CGFloat(totalHeight)
}
可能适合你
答案 1 :(得分:0)
尝试向内容视图中的标签添加约束。
例如为: 左 - 8分 最高 - 8分 对 - 8分 底部 - 8分
现在它应该留在牢房内。
答案 2 :(得分:0)
您需要添加heightForRowAtIndexPath
以自动将单元格高度调整为其内容。
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
return UITableViewAutomaticDimension
}
答案 3 :(得分:0)
查看输出的屏幕截图。对于标签,您应该给出所有四个约束(顶部:5,底部:5,左:5,右:5),您必须将标签的优先级更改为750& 5。将拥抱和阻力优先级设置为1000.然后,您必须在故事板中将行数更改为0
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 250
}