UILabel+GJRatioAutoLayout.m 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //
  2. // UILabel+GJRatioAutoLayout.m
  3. // GJRatioAutoLayout
  4. //
  5. // Created by wangyutao on 15/12/30.
  6. // Copyright © 2015年 wangyutao. All rights reserved.
  7. //
  8. #import "UILabel+GJRatioAutoLayout.h"
  9. #import "UIView+GJRatioAutoLayout.h"
  10. #import "GJRatioAutoLayoutDefine.h"
  11. #import <objc/runtime.h>
  12. @interface UILabel (_GJRatioAutoLayoutStroge)
  13. @property (nonatomic, assign) CGFloat gj_originalFontSize;
  14. @end
  15. @implementation UILabel (_GJRatioAutoLayoutStroge)
  16. - (void)setGj_originalFontSize:(CGFloat)originalFontSize {
  17. objc_setAssociatedObject(self, @selector(gj_originalFontSize), @(originalFontSize), OBJC_ASSOCIATION_RETAIN);
  18. }
  19. - (CGFloat)gj_originalFontSize {
  20. #if CGFLOAT_IS_DOUBLE
  21. return [objc_getAssociatedObject(self, _cmd) doubleValue];
  22. #else
  23. return [objc_getAssociatedObject(self, _cmd) floatValue];
  24. #endif
  25. }
  26. @end
  27. @implementation UILabel (GJRatioAutoLayout)
  28. + (void)load {
  29. GJExchangeImplementations(self, @selector(setPreferredMaxLayoutWidth:), @selector(gj_setPreferredMaxLayoutWidth:));
  30. }
  31. #pragma mark- aLRatio rewrite
  32. - (void)setALRatio:(BOOL)aLRatio {
  33. if (self.gj_aLRatio == aLRatio) return;
  34. [super setALRatio:aLRatio];
  35. //reset only when changed
  36. [self resetFont];
  37. [self resetPreferredMaxLayoutWidth];
  38. }
  39. #pragma mark - preferredMaxLayoutWidth
  40. //scaled when user set by code.
  41. - (void)gj_setPreferredMaxLayoutWidth:(CGFloat)width {
  42. CGFloat maxWidth = width;
  43. if (self.gj_aLRatio && maxWidth > 0) {
  44. maxWidth *= GJ_Scale;
  45. }
  46. [self gj_setPreferredMaxLayoutWidth:maxWidth];
  47. }
  48. #pragma mark- private method
  49. - (void)resetFont {
  50. if (self.gj_aLRatio) {
  51. self.gj_originalFontSize = self.font.pointSize;
  52. CGFloat size = floorl(self.font.pointSize * GJ_Scale);
  53. NSString *name = self.font.fontName;
  54. self.font = [UIFont fontWithName:name size:size];
  55. }
  56. else {
  57. self.font = [UIFont fontWithName:self.font.fontName size:self.gj_originalFontSize];
  58. }
  59. }
  60. - (void)resetPreferredMaxLayoutWidth {
  61. if (self.gj_aLRatio && self.preferredMaxLayoutWidth > 0) {
  62. [self gj_setPreferredMaxLayoutWidth:self.preferredMaxLayoutWidth * GJ_Scale];
  63. }
  64. }
  65. @end