IOS UILabel text is automatically aligned in the upper left corner
In iOS, the default UILabel is vertically centered and aligned. If the height set by UILabel is large, the UILabel is automatically centered vertically when the content is small.
Create a UILabel category
The Code is as follows:
#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
When necessary, you only need to call it directly.
#import UILabel+LeftTopAlign.h-(void)someMethod:(UILabel*)label{ [label textLeftTopAlign];}