UIlabel居上对齐遇到的问题和解决方法以及其他相关资料

UILabel的text的对其方式有四种类型

NSTextAlignmentLeft;
NSTextAlignmentCenter;
NSTextAlignmentRight;

 基本够用 但是今天遇到个问题 就是当我label很高字体很小的时候 默认的label文字永远是默认在中间  上图

[myLabel sizeToFit];首先试了这个方法 但是发现改变大小适应这个属性 会让文字在左上角并且label的height也随之缩小 添加numberToLine=0可以在换行的时候改变高度  其实这个属性就是将大小适应了文字
还是达不到要求
于是继续
重写一个label的drawInRect方法
在继承UILabel里的
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
    CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines]; 
    textRect.origin.y = bounds.origin.y; 
    return textRect;
}
-(void)drawTextInRect:(CGRect)requestedRect { 
    CGRect actualRect = [self textRectForBounds:requestedRect limitedToNumberOfLines:self.numberOfLines]; 
    [super drawTextInRect:actualRect];
}

在外国网站上也有重写UILabel改变对齐方式的方法 并且比较全面 不仅顶部对齐 底部对齐 各种对齐 链接如下:http://blog.csdn.net/yexiaozi_007/article/details/8636522


原文地址:https://www.cnblogs.com/wangxiaoqi/p/6398311.html