前端之家收集整理的这篇文章主要介绍了
swift 根据字符串数量动态计算行高)(>=iOS7.0),
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
- //MARK: - 动态 计算行高,根据字符串的实际内容的多少 在固定的宽度和字体的大小,动态的计算出实际的高度
- func textHeightFromTextString(text: String,textWidth: CGFloat,fontSize: CGFloat,isBold: Bool) -> CGFloat
- {
-
- if (getCurrentIOS() >= 7.0)
- {
- //iOS7之后
- var dict: NSDictionary = NSDictionary()
- if (isBold) {
- dict = NSDictionary(object: UIFont.boldSystemFontOfSize(fontSize),forKey: NSFontAttributeName)
-
- } else {
- dict = NSDictionary(object: UIFont.systemFontOfSize(fontSize),forKey: NSFontAttributeName)
-
- }
-
- let rect: CGRect = (text as NSString).boundingRectWithSize(CGSizeMake(textWidth,CGFloat(MAXFLOAT)),options: [NSStringDrawingOptions.TruncatesLastVisibleLine,NSStringDrawingOptions.UsesFontLeading,NSStringDrawingOptions.UsesLineFragmentOrigin],attributes: dict as? [String : AnyObject],context: nil)
- return rect.size.height
- } else
- {
- //iOS7之前
-
-
- return 0.0
- }
-
- }
- //MARK: - 获取版本号
- func getCurrentIOS() -> Double
- {
-
- return (UIDevice.currentDevice().systemVersion as NSString).doubleValue
-
- }
- //改变对应frame
-
- var frame = self.titleLab!.frame
- frame.size.height = textHeightFromTextString(model.title!,textWidth: self.titleLab!.frame.size.width,fontSize: 19,isBold: true)
- self.titleLab!.frame = frame