應(yīng)用場景,使用輕量級UILabel實現(xiàn)文字居上顯示,或者居下顯示的特殊UI要求下,使用頻率不高(使用UITextview和UITextFiled也可以做,但是個人感覺不太合適)
代碼如下:
LQLable.h
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, LQTextAlignment) {
LQTextAlignmentTop,
LQTextAlignmentMiddle,
LQTextAlignmentBottom,
};
@interface LQLabel : UILabel
@property (nonatomic, assign) LQTextAlignment textAlignment;
@end
LQLable.m
#import "LQLabel.h"
@interface LQLabel ()
@end
@implementation LQLabel
@synthesize textAlignment = textAlignment_;
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
self.textAlignment = LQTextAlignmentMiddle;
}
return self;
}
-(void)setTextAlignment:(LQTextAlignment)textAlignment {
textAlignment_ = textAlignment;
[self setNeedsDisplay];
}
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
switch (self.textAlignment) {
case LQTextAlignmentTop:
textRect.origin.y = bounds.origin.y;
break;
case LQTextAlignmentBottom:
textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;
break;
case LQTextAlignmentMiddle:
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
備注:如有不足請告知??