iOS的UILabel设置上部对齐,中间对齐,底部对齐

.h 文件

typedef NS_ENUM (NSInteger ,VerticalAlignment){

VerticalAlignmentTop = 0,  //上居中

VerticalAlignmentMiddle, //中居中

VerticalAlignmentBottom //低居中

};

@interface VerticalLabel : UILabel

{

@private

VerticalAlignment _verticalAlignment;

}

@property (nonatomic,assign)VerticalAlignment verticalAlignment;

@end

.m文件

@implementation VerticalLabel

@synthesize verticalAlignment = _verticalAlignment;

-(instancetype)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 = 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];

}

使用此类:请看下面的使用的例子


VerticalLabel *textLabel = [[VerticalLabel alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];

textLabel.numberOfLines = 1;

textLabel.font = [UIFont systemFontOfSize:18];

textLabel.text = @"哈哈哈哈哈";

textLabel.textColor = [UIColor redColor];

textLabel.backgroundColor = [UIColor greenColor ];

textLabel.verticalAlignment = VerticalAlignmentTop;

textLabel.textAlignment = NSTextAlignmentRight;

[self.view addSubview:textLabel];

搭配系统的属性textAlignment,可以组成左上角对齐,右上角对齐,左居中对齐,右居中对齐,左下角对齐,右下角对齐,居中。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容