2
0

MWCaptionView.m 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //
  2. // MWCaptionView.m
  3. // MWPhotoBrowser
  4. //
  5. // Created by Michael Waterfall on 30/12/2011.
  6. // Copyright (c) 2011 __MyCompanyName__. All rights reserved.
  7. //
  8. #import "MWCommon.h"
  9. #import "MWCaptionView.h"
  10. #import "MWPhoto.h"
  11. static const CGFloat labelPadding = 10;
  12. // Private
  13. @interface MWCaptionView () {
  14. id <MWPhoto> _photo;
  15. UILabel *_label;
  16. }
  17. @end
  18. @implementation MWCaptionView
  19. - (id)initWithPhoto:(id<MWPhoto>)photo {
  20. self = [super initWithFrame:CGRectMake(0, 0, 320, 44)]; // Random initial frame
  21. if (self) {
  22. self.userInteractionEnabled = NO;
  23. _photo = photo;
  24. self.barStyle = UIBarStyleBlackTranslucent;
  25. self.tintColor = nil;
  26. self.barTintColor = nil;
  27. self.barStyle = UIBarStyleBlackTranslucent;
  28. [self setBackgroundImage:nil forToolbarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
  29. self.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
  30. [self setupCaption];
  31. }
  32. return self;
  33. }
  34. - (CGSize)sizeThatFits:(CGSize)size {
  35. CGFloat maxHeight = 9999;
  36. if (_label.numberOfLines > 0) maxHeight = _label.font.leading*_label.numberOfLines;
  37. CGSize textSize = [_label.text boundingRectWithSize:CGSizeMake(size.width - labelPadding*2, maxHeight)
  38. options:NSStringDrawingUsesLineFragmentOrigin
  39. attributes:@{NSFontAttributeName:_label.font}
  40. context:nil].size;
  41. return CGSizeMake(size.width, textSize.height + labelPadding * 2);
  42. }
  43. - (void)setupCaption {
  44. _label = [[UILabel alloc] initWithFrame:CGRectIntegral(CGRectMake(labelPadding, 0,
  45. self.bounds.size.width-labelPadding*2,
  46. self.bounds.size.height))];
  47. _label.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
  48. _label.opaque = NO;
  49. _label.backgroundColor = [UIColor clearColor];
  50. _label.textAlignment = NSTextAlignmentCenter;
  51. _label.lineBreakMode = NSLineBreakByWordWrapping;
  52. _label.numberOfLines = 0;
  53. _label.textColor = [UIColor whiteColor];
  54. _label.font = [UIFont systemFontOfSize:17];
  55. if ([_photo respondsToSelector:@selector(caption)]) {
  56. _label.text = [_photo caption] ? [_photo caption] : @" ";
  57. }
  58. [self addSubview:_label];
  59. }
  60. @end