(1) .h文件
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, VerticalAlignment)
{
VerticalAlignmentTop = 0, // default
VerticalAlignmentMiddle,
VerticalAlignmentBottom,
};
@interface YLVerticalAlignmentLabel : UILabel
@property (nonatomic) VerticalAlignment verticalAlignment;
@end
(2).m文件
#import "YLVerticalAlignmentLabel.h"
@implementation YLVerticalAlignmentLabel
- (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:
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
0816更新-----支持xib
.h文件
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, VerticalAlignment)
{
VerticalAlignmentTop = 0, // 上对齐
VerticalAlignmentMiddle,//居中
VerticalAlignmentBottom,//底部对齐
};
IB_DESIGNABLE
@interface YLVerticalAlignmentLabel : UILabel
#if TARGET_INTERFACE_BUILDER
@property (nonatomic, assign) IBInspectable NSUInteger verticalAlignment;
#else
@property (nonatomic,assign) VerticalAlignment verticalAlignment;
#endif
@end
Demo地址:
https://github.com/yongliangP/YLVerticalAlignmentLabelDemo