iOS開發(fā)之UILable文字 居上對(duì)齊/居中對(duì)齊/居下對(duì)齊

demo效果圖:
Paste_Image.png
使用方式:

1>將"MyLable"拖到項(xiàng)目中,需要調(diào)用的地方導(dǎo)入頭文件


Paste_Image.png

MyLable.h文件

#import <UIKit/UIKit.h>
typedef enum
{
    VerticalAlignmentTop = 0, // default
    VerticalAlignmentMiddle,
    VerticalAlignmentBottom,
} VerticalAlignment;
@interface MyLable : UILabel
{
@private
    VerticalAlignment _verticalAlignment;
}

@property (nonatomic) VerticalAlignment verticalAlignment;

-(void)setVerticalAlignment:(VerticalAlignment)verticalAlignment;
@end

MyLable.m文件

#import "MyLable.h"

@implementation MyLable
@synthesize verticalAlignment = verticalAlignment_;

-(id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.verticalAlignment = VerticalAlignmentMiddle;
    }
    return self;
}

-(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:
            // Fall through.
        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

2>一句代碼調(diào)用,例如

居上對(duì)齊
居中對(duì)齊
居下對(duì)齊

感謝原作者的demo,以下是參考來源:
http://code.cocoachina.com/view/134318
https://github.com/OwenJoe/LableAlignment.git

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

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,176評(píng)論 25 708
  • “如無必要,勿增實(shí)體”是由14世紀(jì)邏輯學(xué)家、圣方濟(jì)各會(huì)修士奧卡姆的威廉(William of Occam,約128...
    浮塵過隙閱讀 2,628評(píng)論 0 1
  • 如果對(duì)象是NSString、NSDictionary、NSArray、NSData、NSNumber等類型,可以直...
    CoderRH閱讀 1,678評(píng)論 1 3
  • 文/左航道 我來北京了。這不是一個(gè)帶著豪邁語(yǔ)氣的句子。盡管,它一般會(huì)被這樣看。但它的確不是。它應(yīng)有的語(yǔ)氣應(yīng)該是不夠...
    燈火讀書閱讀 256評(píng)論 0 0
  • 輕分享是饑人谷不定期舉行的,以谷里小伙伴為主講者,給大家分享自身的前端學(xué)習(xí)方法,技能知識(shí),項(xiàng)目經(jīng)驗(yàn),求職經(jīng)驗(yàn)的免費(fèi)...
    饑人谷_青青閱讀 1,109評(píng)論 1 1

友情鏈接更多精彩內(nèi)容