調(diào)整UILabel文字的位置

Simulator Screen Shot 2016年8月16日 下午4.36.56.png

(1) .h文件
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, VerticalAlignment)
{
VerticalAlignmentTop = 0, // default
VerticalAlignmentMiddle,
VerticalAlignmentBottom,
};

@interface YLVerticalAlignmentLabel : UILabel

@property (nonatomic) VerticalAlignment verticalAlignment;

@end

(2).m文件
#import "YLVerticalAlignmentLabel.h"

@implementation YLVerticalAlignmentLabel

- (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:

    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
0816更新-----支持xib

.h文件

#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, VerticalAlignment)
{
    VerticalAlignmentTop = 0, // 上對(duì)齊
    VerticalAlignmentMiddle,//居中
    VerticalAlignmentBottom,//底部對(duì)齊
};

IB_DESIGNABLE
@interface YLVerticalAlignmentLabel : UILabel

#if TARGET_INTERFACE_BUILDER
@property (nonatomic, assign) IBInspectable NSUInteger verticalAlignment;
#else
@property (nonatomic,assign) VerticalAlignment verticalAlignment;
#endif
@end

Demo地址:
https://github.com/yongliangP/YLVerticalAlignmentLabelDemo

最后編輯于
?著作權(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)容

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