程序员人生 网站导航

iOS UILabel 文字自动左上角对齐

栏目:综合技术时间:2016-03-17 11:48:23

iOS中默许的UILabel是垂直居中对齐的,如果UILabel设置的高度较大,当内容少的时候,会自动垂直居中。

创建1个  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)⑸, labelSize.height); self.frame = dateFrame; } @end

在需要的时候,只需要直接调用便可。

#import "UILabel+LeftTopAlign.h" -(void)someMethod:(UILabel*)label { [label textLeftTopAlign]; }

------分隔线----------------------------
------分隔线----------------------------

最新技术推荐