demo效果图:
使用方式:
1>将"MyLable"拖到项目中,需要调用的地方导入头文件
MyLable.h文件
#import <UIKit/UIKit.h>
typedef enum
{
VerticalAlignmentTop = 0, // default
VerticalAlignmentMiddle,
VerticalAlignmentBottom,
} VerticalAlignment;
@interface MyLable : UILabel
{
@private
VerticalAlignment _verticalAlignment;
}
@property (nonatomic) VerticalAlignment verticalAlignment;
-(void)setVerticalAlignment:(VerticalAlignment)verticalAlignment;
@end
MyLable.m文件
#import "MyLable.h"
@implementation MyLable
@synthesize verticalAlignment = verticalAlignment_;
-(id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
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 VerticalAlignmentBottom:
textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;
break;
case VerticalAlignmentMiddle:
// Fall through.
default:
textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0;
}
return textRect;
}
-(void)drawTextInRect:(CGRect)requestedRect {
CGRect actualRect = [self textRectForBounds:requestedRect limitedToNumberOfLines:self.numberOfLines];
[super drawTextInRect:actualRect];
}
@end
2>一句代码调用,例如
感谢原作者的demo,以下是参考来源:
http://code.cocoachina.com/view/134318
https://github.com/OwenJoe/LableAlignment.git