gpt4 book ai didi

ios - 我返回的 UILabel 高度从来不准确

转载 作者:行者123 更新时间:2023-11-29 01:07:24 26 4
gpt4 key购买 nike

我正在 try catch 我的 UILabel 的高度,以便我可以动态设置它的单元格的高度,但它永远不会返回正确的高度,而且实际上,我的内容总是被截断并附加有省略号。

我的代码:

let height   = String(page.valueForKey(subject)).heightWithConstrainedWidth(self.view.frame.width - 30, font: UIFont.systemFontOfSize(16.0))

// and at the bottom of my class..

// Custom functions
extension String {
func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: CGFloat.max)
let boundingBox = self.boundingRectWithSize(constraintRect, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return boundingBox.height
}
}

它绝对是一次勇敢的尝试,因为它返回某种相对较大的动态数字,但数字总是很短而且永远不准确。

我提取高度的方式有什么明显不合适的地方吗?有没有更好的方法来执行此操作?


根据 Matt 的回复,我更新了测量标签的方法:

// Custom functions
extension String {
func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
let label:UILabel = UILabel(frame: CGRectMake(0,0,width, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = .ByWordWrapping
label.font = font
label.text = self
label.sizeToFit()
return label.frame.height
}
}

但是还是不够大..

最佳答案

您的代码就其功能而言没有问题。问题仅仅是标签不是字符串。您正在查找字符串的高度。那不是你想做的。你想找到标签的高度!毕竟,UILabel 不仅仅是它包含的字符串。 UILabel 比字符串高。你没有考虑到这一点。

关于ios - 我返回的 UILabel 高度从来不准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36182863/

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