在IOS中默认的UILabel中的文字是正能是居中对齐的,在应用的时候,我们可能会用到顶部或者底部对齐,下面我们就来实现UILabel的顶部,底部对齐,
实现代码如下
在调用的时候首先引入MyLabel,调用代码如下:
首先新建一个类MyLabel继承自UILabel,代码如下
#import <UIKit/UIKit.h>
typedef enum
{
VerticalAlignmentTop=0,
VerticalAlignmentMiddle,//default
VerticalAlignmentBottom,
}VerticalAlignment;
@interface MyLabel : UILabel
{
@private
VerticalAlignment _verticalAlignment;
}
@property(nonatomic)VerticalAlignment verticalAlignment;
@end
实现代码如下
#import "MyLabel.h"
@implementation MyLabel
@synthesize verticalAlignment=_verticalAlignment;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.verticalAlignment=VerticalAlignmentMiddle;
}
return self;
}
-(void)setVerticalAlignment:(VerticalAlignment)verticalAlignment
{
_verticalAlignment=verticalAlignment;
[self setNeedsDisplay];//重绘一下
}
-(CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
CGRect textRect=[super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
switch(self.verticalAlignment)
{
case VerticalAlignmentTop:
textRect.origin.y=bounds.origin.y;
break;
case VerticalAlignmentMiddle:
textRect.origin.y=bounds.origin.y+(bounds.size.height-textRect.size.height)/2.0;
break;
case VerticalAlignmentBottom:
textRect.origin.y=bounds.origin.y+bounds.size.height-textRect.size.height;
break;
default:
textRect.origin.y=bounds.origin.y+(bounds.size.height-textRect.size.height)/2.0;
break;
}
return textRect;
}
-(void)drawTextInRect:(CGRect)rect
{
CGRect actualRect=[self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];//重新计算位置
[super drawTextInRect:actualRect];
}
@end
在调用的时候首先引入MyLabel,调用代码如下:
MyLabel *lbl = [[MyLabel alloc] initWithFrame:CGRectMake(20, 20, 150, 300)];
lbl.textAlignment = UITextAlignmentCenter;
lbl.textColor = [UIColor redColor];
lbl.lineBreakMode = UILineBreakModeWordWrap;
lbl.numberOfLines = 0;
lbl.text=@"My Content";
[lbl setVerticalAlignment:VerticalAlignmentMiddle];
[self.view addSubview:lbl];