iOS UILabel垂直對齊(上居中)

項目中顯示文本信息的時候,大多使用Label。可是當文字量比較小的時候,咱們定義label.frame較大,這時候文字會自動上下居中顯示,不符合咱們的要求,而且UIlabel也沒有提供相應的屬性或者方法來知足咱們的要求。爲了知足需求,我以前的方法都是計算文字的長度,而後再設置label的frame。後來看到了一篇文章,實現了label的上居中。本身實現了一下,基本知足的需求,下面就是實現一個簡單的垂直居中的label。bash

YXLabel.h字體

#import <UIKit/UIKit.h>

typedef NS_ENUM (NSInteger ,VerticalAlignment){
    
    VerticalAlignmentTop = 0,  //上居中
    
    VerticalAlignmentMiddle, //中居中
    
    VerticalAlignmentBottom //低居中
    
};
//繼承UILabel
@interface YXLabel : UILabel
//垂直居中屬性
@property (nonatomic,assign)VerticalAlignment verticalAlignment;

@end

複製代碼

YXLabel.mui

#import "YXLabel.h"

@implementation YXLabel

-(instancetype)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 = self.bounds.origin.y;
            
            break;
            
        case VerticalAlignmentMiddle:
            
            break;
            
        case VerticalAlignmentBottom:
            
            textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;
            
            break;
            
        default:
            
            textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0;
            
            break;
            
    }
    
    return textRect;
    
}
//重寫父類方法
-(void)drawTextInRect:(CGRect)rect{
    
    CGRect actualRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];
    
    [super drawTextInRect:actualRect];
    
}

複製代碼
相關文章
相關標籤/搜索