在iOS開發中常常會用到label,能夠多行顯示,可是當數據少的時候可能沒有那麼多行,就會在中間顯示,若是想讓它在左上對其,彷佛要費一番功夫,一下是我總結的三種方法。ios
- (void)viewDidLoad {測試
[super viewDidLoad];spa
NSString *string=@"爲了測試label的顯示方法,因此字符串的長度要長一些!!爲了測試label的顯示方法,因此字符串的長度要長一些!!爲了測試label的顯示方法,因此字符串的長度要長一些!!";.net
_label=[[UILabel alloc]initWithFrame:CGRectMake(20, 50, SCREEN_WIDTH-40, 300)];3d
_label.backgroundColor=[UIColor groupTableViewBackgroundColor];orm
_label.numberOfLines=0;繼承
_label.text=string;開發
[self.view addSubview:_label];字符串
}get
結果是這樣的
方法1:
而後在viewDidLayoutSubviews方法中調用sizeToFit 記住必定是這個方法裏
-(void)viewDidLayoutSubviews{
[self.label sizeToFit];
}
結果以下:
方法2:寫一個分類,從新設置frame
#import <UIKit/UIKit.h>
@interface UILabel (TopLeftLabel)
- (void)setTopAlignmentWithText:(NSString *)text maxHeight:(CGFloat)maxHeight;
@end
.m文件中
#import "UILabel+TopLeftLabel.h"
@implementation UILabel (TopLeftLabel)
- (void)setTopAlignmentWithText:(NSString *)text maxHeight:(CGFloat)maxHeight
{
CGRect frame = self.frame;
CGSize size = [text sizeWithFont:self.font constrainedToSize:CGSizeMake(frame.size.width, maxHeight)];
frame.size = CGSizeMake(frame.size.width, size.height);
self.frame = frame;
self.text = text;
}
@end
用的時候直接調用
[_label setTopAlignmentWithText:string maxHeight:300];
下面是效果圖
方法3:
3.重寫drawRect方法 繼承UILabel重寫drawRect方法
#import <UIKit/UIKit.h>
@interface TopLeftLabel : UILabel
@end
.m文件中
#import "TopLeftLabel.h"
@implementation TopLeftLabel
- (id)initWithFrame:(CGRect)frame {
return [super initWithFrame:frame];
}
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
textRect.origin.y = bounds.origin.y;
return textRect;
}
-(void)drawTextInRect:(CGRect)requestedRect {
CGRect actualRect = [self textRectForBounds:requestedRect limitedToNumberOfLines:self.numberOfLines];
[super drawTextInRect:actualRect];
}
@end
用的時候直接繼承這個label就好
NSString *string=@"爲了測試label的顯示方法,因此字符串的長度要長一些!!爲了測試label的顯示方法,因此字符串的長度要長一些!!爲了測試label的顯示方法,因此字符串的長度要長一些!!";
_label=[[TopLeftLabel alloc]initWithFrame:CGRectMake(20, 50, SCREEN_WIDTH-40, 300)];
_label.backgroundColor=[UIColor groupTableViewBackgroundColor];
_label.numberOfLines=0;
_label.text=string;
[self.view addSubview:_label];
下面是效果圖: