MASExampleLabelView.m 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // MASExampleLabelView.m
  3. // Masonry iOS Examples
  4. //
  5. // Created by Jonas Budelmann on 24/10/13.
  6. // Copyright (c) 2013 Jonas Budelmann. All rights reserved.
  7. //
  8. #import "MASExampleLabelView.h"
  9. static UIEdgeInsets const kPadding = {10, 10, 10, 10};
  10. @interface MASExampleLabelView ()
  11. @property (nonatomic, strong) UILabel *shortLabel;
  12. @property (nonatomic, strong) UILabel *longLabel;
  13. @end
  14. @implementation MASExampleLabelView
  15. - (id)init {
  16. self = [super init];
  17. if (!self) return nil;
  18. // text courtesy of http://baconipsum.com/
  19. self.shortLabel = UILabel.new;
  20. self.shortLabel.numberOfLines = 1;
  21. self.shortLabel.textColor = [UIColor purpleColor];
  22. self.shortLabel.lineBreakMode = NSLineBreakByTruncatingTail;
  23. self.shortLabel.text = @"Bacon";
  24. [self addSubview:self.shortLabel];
  25. self.longLabel = UILabel.new;
  26. self.longLabel.numberOfLines = 8;
  27. self.longLabel.textColor = [UIColor darkGrayColor];
  28. self.longLabel.lineBreakMode = NSLineBreakByTruncatingTail;
  29. self.longLabel.text = @"Bacon ipsum dolor sit amet spare ribs fatback kielbasa salami, tri-tip jowl pastrami flank short loin rump sirloin. Tenderloin frankfurter chicken biltong rump chuck filet mignon pork t-bone flank ham hock.";
  30. [self addSubview:self.longLabel];
  31. [self.longLabel makeConstraints:^(MASConstraintMaker *make) {
  32. make.left.equalTo(self.left).insets(kPadding);
  33. make.top.equalTo(self.top).insets(kPadding);
  34. }];
  35. [self.shortLabel makeConstraints:^(MASConstraintMaker *make) {
  36. make.centerY.equalTo(self.longLabel.centerY);
  37. make.right.equalTo(self.right).insets(kPadding);
  38. }];
  39. return self;
  40. }
  41. - (void)layoutSubviews {
  42. [super layoutSubviews];
  43. // for multiline UILabel's you need set the preferredMaxLayoutWidth
  44. // you need to do this after [super layoutSubviews] as the frames will have a value from Auto Layout at this point
  45. // stay tuned for new easier way todo this coming soon to Masonry
  46. CGFloat width = CGRectGetMinX(self.shortLabel.frame) - kPadding.left;
  47. width -= CGRectGetMinX(self.longLabel.frame);
  48. self.longLabel.preferredMaxLayoutWidth = width;
  49. // need to layoutSubviews again as frames need to recalculated with preferredLayoutWidth
  50. [super layoutSubviews];
  51. }
  52. @end