自定義UILabel設置垂直方向的居上,居中,居下

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的設置方法atom

@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
相關文章
相關標籤/搜索