Swift - 计算文本高度

前端之家收集整理的这篇文章主要介绍了Swift - 计算文本高度前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

http://www.cnblogs.com/YouXianMing/p/5823893.html

  1. //
  2. // String+StringHeight.swift
  3. // StringHeight
  4. //
  5. // Created by YouXianMing on 16/8/30.
  6. // Copyright © 2016年 YouXianMing. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10.  
  11. extension String {
  12. /**
  13. Get the height with the string.
  14. - parameter attributes: The string attributes.
  15. - parameter fixedWidth: The fixed width.
  16. - returns: The height.
  17. */
  18. func heightWithStringAttributes(attributes : [String : AnyObject],fixedWidth : CGFloat) -> CGFloat {
  19. guard self.characters.count > 0 && fixedWidth > 0 else {
  20. return 0
  21. }
  22. let size = CGSizeMake(fixedWidth,CGFloat.max)
  23. let text = self as NSString
  24. let rect = text.boundingRectWithSize(size,options:.UsesLineFragmentOrigin,attributes: attributes,context:nil)
  25. return rect.size.height
  26. }
  27. /**
  28. Get the height with font.
  29. - parameter font: The font.
  30. - parameter fixedWidth: The fixed width.
  31. - returns: The height.
  32. */
  33. func heightWithFont(font : UIFont = UIFont.systemFontOfSize(18),fixedWidth : CGFloat) -> CGFloat {
  34. guard self.characters.count > 0 && fixedWidth > 0 else {
  35. return 0
  36. }
  37. let size = CGSizeMake(fixedWidth,attributes: [NSFontAttributeName : font],context:nil)
  38. return rect.size.height
  39. }
  40. /**
  41. Get the width with the string.
  42. - parameter attributes: The string attributes.
  43. - returns: The width.
  44. */
  45. func widthWithStringAttributes(attributes : [String : AnyObject]) -> CGFloat {
  46. guard self.characters.count > 0 else {
  47. return 0
  48. }
  49. let size = CGSizeMake(CGFloat.max,0)
  50. let text = self as NSString
  51. let rect = text.boundingRectWithSize(size,context:nil)
  52. return rect.size.width
  53. }
  54. /**
  55. Get the width with the string.
  56. - parameter font: The font.
  57. - returns: The string's width.
  58. */
  59. func widthWithFont(font : UIFont = UIFont.systemFontOfSize(18)) -> CGFloat {
  60. guard self.characters.count > 0 else {
  61. return 0
  62. }
  63. let size = CGSizeMake(CGFloat.max,context:nil)
  64. return rect.size.width
  65. }
  66. }

猜你在找的Swift相关文章