iOS中默认的UILabel是垂直居中对齐的,如果UILabel设置的高度较大,当内容少的时候,会自动垂直居中。
创建一个 UILabel的category
代码如下:
#import
@interface UILabel (LeftTopAlign)
- (void) textLeftTopAlign;
@end
#import UILabel+LeftTopAlign.h
@implementation UILabel (LeftTopAlign)
- (void) textLeftTopAlign
{
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:12.f], NSParagraphStyleAttributeName:paragraphStyle.copy};
CGSize labelSize = [self.text boundingRectWithSize:CGSizeMake(207, 999) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
CGRect dateFrame =CGRectMake(2, 140, CGRectGetWidth(self.frame)-5, labelSize.height);
self.frame = dateFrame;
}
@end
在需要的时候,只需要直接调用即可。
#import UILabel+LeftTopAlign.h
-(void)someMethod:(UILabel*)label
{
[label textLeftTopAlign];
}
网友评论