MWCaptionView.m 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. [self layoutIfNeeded];
  32. }
  33. return self;
  34. }
  35. - (CGSize)sizeThatFits:(CGSize)size {
  36. CGFloat maxHeight = 9999;
  37. if (_label.numberOfLines > 0) maxHeight = _label.font.leading*_label.numberOfLines;
  38. CGSize textSize = [_label.text boundingRectWithSize:CGSizeMake(size.width - labelPadding*2, maxHeight)
  39. options:NSStringDrawingUsesLineFragmentOrigin
  40. attributes:@{NSFontAttributeName:_label.font}
  41. context:nil].size;
  42. return CGSizeMake(size.width, textSize.height + labelPadding * 2);
  43. }
  44. - (void)setupCaption {
  45. _label = [[UILabel alloc] initWithFrame:CGRectIntegral(CGRectMake(labelPadding, 0,
  46. self.bounds.size.width-labelPadding*2,
  47. self.bounds.size.height))];
  48. _label.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
  49. _label.opaque = NO;
  50. _label.backgroundColor = [UIColor clearColor];
  51. _label.textAlignment = NSTextAlignmentCenter;
  52. _label.lineBreakMode = NSLineBreakByWordWrapping;
  53. _label.numberOfLines = 0;
  54. _label.textColor = [UIColor whiteColor];
  55. _label.font = [UIFont systemFontOfSize:17];
  56. if ([_photo respondsToSelector:@selector(caption)]) {
  57. _label.text = [_photo caption] ? [_photo caption] : @" ";
  58. }
  59. [self addSubview:_label];
  60. }
  61. @end