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]; }