调整UILabel文字的位置

作者: iceMaple | 来源:发表于2016-08-02 16:10 被阅读1346次
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, // 上对齐
    VerticalAlignmentMiddle,//居中
    VerticalAlignmentBottom,//底部对齐
};

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

相关文章

网友评论

    本文标题:调整UILabel文字的位置

    本文链接:https://www.haomeiwen.com/subject/qggfsttx.html