本文介绍了将UILabel高度调整为文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些标签,我想调整它们的文字高度,这是我现在为此写的代码
I have some labels which I want to adjust their height to the text, this is the code I wrote for this now
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
编辑:
问题是不是在这段代码中,所以我的修复本身就是问题。对于其他人来说它可能仍然有用!
The issue was not in this piece of code, so my fix is in the question itself. It might still be useful for others!
推荐答案
我刚把它放在操场上,它对我有用。
I've just put this in a playground and it works for me.
针对Swift 4.0进行了更新
import UIKit
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
let font = UIFont(name: "Helvetica", size: 20.0)
var height = heightForView("This is just a load of text", font: font, width: 100.0)
Swift 3:
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
这篇关于将UILabel高度调整为文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!