前言:做過(guò)iOS 的都知道根资,UILabel有讓文字居左费坊,居右倒槐,居中的屬性,可是有時(shí)候我們?cè)谧鲰?xiàng)目的時(shí)候葵萎,可能會(huì)需要將label上的文字居上导犹, 居中或者 居下這樣的操作唱凯。那么今天我們就來(lái)說(shuō)一說(shuō)這種效果的實(shí)現(xiàn)方式羡忘。
#import <UIKit/UIKit.h>
typedefenum
{
VerticalAlignmentTop =0,// default
VerticalAlignmentMiddle,
VerticalAlignmentBottom,
} VerticalAlignment;
@interfaceBaseUILabel :UILabel
{
@private
VerticalAlignment_verticalAlignment;
}
@property(nonatomic)VerticalAlignmentverticalAlignment;
@end
#import"BaseUILabel.h"
@implementationBaseUILabel
@synthesizeverticalAlignment =verticalAlignment_;
- (id)initWithFrame:(CGRect)frame {
if(self= [superinitWithFrame:frame]) {
self.verticalAlignment=VerticalAlignmentMiddle;
}
returnself;
}
- (void)setVerticalAlignment:(VerticalAlignment)verticalAlignment {
verticalAlignment_= verticalAlignment;
[selfsetNeedsDisplay];
}
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
CGRecttextRect = [supertextRectForBounds:boundslimitedToNumberOfLines:numberOfLines];
switch(self.verticalAlignment) {
caseVerticalAlignmentTop:
textRect.origin.y= bounds.origin.y;
break;
caseVerticalAlignmentBottom:
textRect.origin.y= bounds.origin.y+ bounds.size.height- textRect.size.height;
break;
caseVerticalAlignmentMiddle:
// Fall through.
default:
textRect.origin.y= bounds.origin.y+ (bounds.size.height- textRect.size.height) /2.0;
}
returntextRect;
}
-(void)drawTextInRect:(CGRect)requestedRect {
CGRectactualRect = [selftextRectForBounds:requestedRectlimitedToNumberOfLines:self.numberOfLines];
[superdrawTextInRect:actualRect];
}
@end
這樣我們?cè)谑褂玫臅r(shí)候谎痢,只要繼承這個(gè)label類,然后選擇想要實(shí)現(xiàn)效果的屬性即可