Skip to content

Instantly share code, notes, and snippets.

@yume190
Created June 22, 2014 03:37
Show Gist options
  • Save yume190/966931148c17298533b0 to your computer and use it in GitHub Desktop.
Save yume190/966931148c17298533b0 to your computer and use it in GitHub Desktop.
ivan.m 垂直式對齊 UILabel(https://discussions.apple.com/thread/1759957?tstart=0
// Label2.mm
// (c) 2009 Ivan Misuno, www.cuberoom.biz
#import "Label2.h"
@implementation Label2
-(id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (!self) return nil;
_verticalAlignment = VerticalAlignmentTop;
return self;
}
-(void)dealloc
{
[super dealloc];
}
-(VerticalAlignment) verticalAlignment
{
return _verticalAlignment;
}
-(void) setVerticalAlignment:(VerticalAlignment)value
{
_verticalAlignment = value;
[self setNeedsDisplay];
}
// align text block according to vertical alignment settings
-(CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
CGRect rect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
CGRect result;
switch (_verticalAlignment)
{
case VerticalAlignmentTop:
result = CGRectMake(bounds.origin.x, bounds.origin.y, rect.size.width, rect.size.height);
break;
case VerticalAlignmentMiddle:
result = CGRectMake(bounds.origin.x, bounds.origin.y + (bounds.size.height - rect.size.height) / 2, rect.size.width, rect.size.height);
break;
case VerticalAlignmentBottom:
result = CGRectMake(bounds.origin.x, bounds.origin.y + (bounds.size.height - rect.size.height), rect.size.width, rect.size.height);
break;
default:
result = bounds;
break;
}
return result;
}
-(void)drawTextInRect:(CGRect)rect
{
CGRect r = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];
[super drawTextInRect:r];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment