寫一個方法來繼承String
//自動控制文字換行及寬度
extension String {
func textSizeWithFont(font: UIFont, constrainedToSize size:CGSize) -> CGSize {
var textSize:CGSize!
if CGSizeEqualToSize(size, CGSizeZero) {
let attributes = NSDictionary(object: font, forKey: NSFontAttributeName)
textSize = self.sizeWithAttributes(attributes as! [String : AnyObject] as [String : AnyObject])
} else {
let option = NSStringDrawingOptions.UsesLineFragmentOrigin
let attributes = NSDictionary(object: font, forKey: NSFontAttributeName)
let stringRect = self.boundingRectWithSize(size, options: option, attributes: attributes as! [String : AnyObject] as [String : AnyObject], context: nil)
textSize = stringRect.size
}
return textSize
}
}
用法:
let PRojectText="我是一段字符串,來計算我的高度吧";
let projectSize=projectText.textSizeWithFont(UIFont.systemFontOfSize(14), constrainedToSize:CGSizeMake(100, 200))
let comProjectW:CGFloat=projectSize.width;
let comProjectH:CGFloat=projectSize.height;
//記得要在計算的字符串UILable中加上
UIlable.font=UIFont.systemFontOfSize(14);
//顯示幾行
UIlable.numberOfLines=1;
UIlable.frame = CGRectMake(50, 50, comProjectW, comProjectH);
新聞熱點
疑難解答