IOS系統框架中UILabel的屬性textAlignment只調整水平方向的居中,居左,居右,而沒有垂直方向的調整。所以要自定義一個繼承自UILabel的類,在類的實現文件中進行文字的重繪,達到垂直方向的位置調整。
新建一個類文件,繼承自UILabel,頭文件如下:
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSInteger,VerticalAlignment){
VerticalAlignmentTop,
VerticalAlignmentMiddle,
VerticalAlignmentBottom
};
@interface FSVerticallyAlignedLabel : UILabel
@property (nonatomic,assign) VerticalAlignment verticalAlignment;
@end
在.m文件中,實現verticalAlignment的設置方法
@implementation FSVerticallyAlignedLabel
- (id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
self.verticalAlignment = VerticalAlignmentMiddle;
}
return self;
}
/**
* 設置屬性方法
*
* @param verticalAlignment 垂直調整位置
*/
- (void)setVerticalAlignment:(VerticalAlignment)verticalAlignment
{
_verticalAlignment = verticalAlignment;
[self setNeedsDisplay];
}
/**
* 計算文字的矩形區域
*
* @param bounds label矩形區域
* @param numberOfLines 行數
*
* @return 返回文字所占的矩形區域
*/
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
//通過設定字體區域的y值來調整垂直位置
switch (self.verticalAlignment) {
case VerticalAlignmentTop:
textRect.origin.y = bounds.origin.y;
break;
case VerticalAlignmentMiddle:
textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0;
break;
case VerticalAlignmentBottom:
textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;
break;
}
return textRect;
}
//重寫父類方法
- (void)drawTextInRect:(CGRect)rect
{
CGRect actualRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];
[super drawTextInRect:actualRect];
}
@end
