在iOS開發(fā)中經(jīng)常會用到label,可以多行顯示,但是當(dāng)數(shù)據(jù)少的時(shí)候可能沒有那么多行,就會在中間顯示,如果想讓它在左上對其,似乎要費(fèi)一番功夫,一下是我總結(jié)的三種方法。
1.sizeToFit 先定義一個(gè)label
- (void)viewDidLoad {
[superviewDidLoad];
NSString*string=@"為了測試label的顯示方法,所以字符串的長度要長一些??!為了測試label的顯示方法,所以字符串的長度要長一些??!為了測試label的顯示方法,所以字符串的長度要長一些!!";
_label=[[UILabelalloc]initWithFrame:CGRectMake(20,50,SCREEN_WIDTH-40,300)];
_label.backgroundColor=[UIColorgroupTableViewBackgroundColor];
_label.numberOfLines=0;
_label.text=string;
[self.viewaddSubview:_label];
}
結(jié)果是這樣的
然后在viewDidLayoutSubviews方法中調(diào)用sizeToFit ?記住一定是這個(gè)方法里
-(void)viewDidLayoutSubviews{
[self.labelsizeToFit];
}
結(jié)果如下:
2.寫一個(gè)分類,重新設(shè)置frame
#import
@interfaceUILabel (TopLeftLabel)
- (void)setTopAlignmentWithText:(NSString*)text maxHeight:(CGFloat)maxHeight;
@end
.m文件中
#import"UILabel+TopLeftLabel.h"
@implementationUILabel (TopLeftLabel)
- (void)setTopAlignmentWithText:(NSString*)text maxHeight:(CGFloat)maxHeight
{
CGRectframe =self.frame;
CGSizesize = [textsizeWithFont:self.fontconstrainedToSize:CGSizeMake(frame.size.width, maxHeight)];
frame.size=CGSizeMake(frame.size.width, size.height);
self.frame= frame;
self.text= text;
}
@end
用的時(shí)候直接調(diào)用
[_labelsetTopAlignmentWithText:stringmaxHeight:300];
下面是效果圖
3.重寫drawRect方法 繼承UILabel重寫drawRect方法
#import
@interfaceTopLeftLabel :UILabel
@end
.m文件中
#import"TopLeftLabel.h"
@implementationTopLeftLabel
- (id)initWithFrame:(CGRect)frame {
return[superinitWithFrame:frame];
}
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
CGRecttextRect = [supertextRectForBounds:boundslimitedToNumberOfLines:numberOfLines];
textRect.origin.y= bounds.origin.y;
returntextRect;
}
-(void)drawTextInRect:(CGRect)requestedRect {
CGRectactualRect = [selftextRectForBounds:requestedRectlimitedToNumberOfLines:self.numberOfLines];
[superdrawTextInRect:actualRect];
}
@end
用的時(shí)候直接集成這個(gè)label就好
NSString*string=@"為了測試label的顯示方法,所以字符串的長度要長一些??!為了測試label的顯示方法,所以字符串的長度要長一些!!為了測試label的顯示方法,所以字符串的長度要長一些??!";
_label=[[TopLeftLabelalloc]initWithFrame:CGRectMake(20,50,SCREEN_WIDTH-40,300)];
_label.backgroundColor=[UIColorgroupTableViewBackgroundColor];
_label.numberOfLines=0;
_label.text=string;
[self.viewaddSubview:_label];
下面是效果圖: