swift 根据字符串数量动态计算行高)(>=iOS7.0)

前端之家收集整理的这篇文章主要介绍了swift 根据字符串数量动态计算行高)(>=iOS7.0)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. //MARK: - 动态 计算行高,根据字符串的实际内容的多少 在固定的宽度和字体的大小,动态的计算出实际的高度
  2. func textHeightFromTextString(text: String,textWidth: CGFloat,fontSize: CGFloat,isBold: Bool) -> CGFloat
  3. {
  4. if (getCurrentIOS() >= 7.0)
  5. {
  6. //iOS7之后
  7. var dict: NSDictionary = NSDictionary()
  8. if (isBold) {
  9. dict = NSDictionary(object: UIFont.boldSystemFontOfSize(fontSize),forKey: NSFontAttributeName)
  10.  
  11. } else {
  12. dict = NSDictionary(object: UIFont.systemFontOfSize(fontSize),forKey: NSFontAttributeName)
  13.  
  14. }
  15. 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)
  16. return rect.size.height
  17. } else
  18. {
  19. //iOS7之前
  20. return 0.0
  21. }
  22. }
  23. //MARK: - 获取版本号
  24. func getCurrentIOS() -> Double
  25. {
  26. return (UIDevice.currentDevice().systemVersion as NSString).doubleValue
  27.  
  28. }
  1. //改变对应frame
  2.  
  3. var frame = self.titleLab!.frame
  4. frame.size.height = textHeightFromTextString(model.title!,textWidth: self.titleLab!.frame.size.width,fontSize: 19,isBold: true)
  5. self.titleLab!.frame = frame

猜你在找的Swift相关文章