【发布时间】:2016-03-24 00:12:46
【问题描述】:
我正在尝试捕获我的 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
}
}
这绝对是一次勇敢的尝试,因为它返回了某种相对较大的动态数字,但该数字总是很短且永远不准确。
我如何提取身高有什么明显不恰当的地方吗?有没有更好的方法来执行此操作?
根据马特的回复,我更新为这样测量标签:
// 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
}
}
但还是不够大..
【问题讨论】:
标签: ios swift uitableview