应用场景,使用轻量级UILabel实现文字居上显示,或者居下显示的特殊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
备注:如有不足请告知😄
网友评论