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