Label垂直對齊(上居中)


感謝作者藍清凡 原文地址 http://www.cnblogs.com/csdnmc/p/5407079.html
項目中顯示文本信息的時候,大多使用Label。但是當文字量比較小的時候,我們定義label.frame較大,這時候文字會自動上下居中顯示,不符合我們的要求,并且UIlabel也沒有提供相應的屬性或者方法來滿足我們的要求。為了滿足需求,我之前的方法都是計算文字的長度,然后再設置label的frame。后來看到了一篇文章,實現了label的上居中。自己實現了一下,基本滿足的需求,下面就是實現一個簡單的垂直居中的label。

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.m

#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];
    
}
/**
 *  計算文字的矩形區(qū)域
 *
 *  @param bounds        label矩形區(qū)域
 *  @param numberOfLines 行數
 *
 *  @return 返回文字所占的矩形區(qū)域
 */
-(CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines{
    
    CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];

    //通過設定字體區(qū)域的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];
    
}

結束。就是這么簡單,分享給大家,希望能幫到大家!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,062評論 25 709
  • -1- 多年來,我媽在家中的地位都是最低的,當然,地位低并不表示不被愛,僅僅是在家中的重要程度低而已。 我,我爸,...
    牧狼天下閱讀 386評論 0 0
  • 開啟蘋果自帶的block代碼塊: 輸入inlineBlock開啟蘋果自帶的block代碼塊 舉個例子 當返回值為i...
    _CLAY_閱讀 455評論 0 0
  • 某天張同學來到了一個拍賣網站,看中了一件心儀的拍品,于是他愉快的參與了競價,并處于了領先的地位,隨后張同學死死盯住...
    鄭印閱讀 3,626評論 7 26
  • 每次下雨天,都會想起一個人,不知道為什么,總覺得那不是應該遇到的人,因為每次想起就有一點心痛,但是想想,或許就是...
    山和風閱讀 822評論 0 0

友情鏈接更多精彩內容