iOS UILabel 左上对齐

iOS开发中经常会用到label,可以多行显示,但是当数据少的时候可能没有那么多行,就会在中间显示,如果想让它在左上对其,似乎要费一番功夫,一下是我总结的三种方法。

- (void)viewDidLoad {

    [super viewDidLoad];

    NSString *string=@"为了测试label的显示方法,所以字符串的长度要长一些!!为了测试label的显示方法,所以字符串的长度要长一些!!为了测试label的显示方法,所以字符串的长度要长一些!!";

    _label=[[UILabel alloc]initWithFrame:CGRectMake(20, 50, SCREEN_WIDTH-40, 300)];

    _label.backgroundColor=[UIColor groupTableViewBackgroundColor];

    _label.numberOfLines=0;

    _label.text=string;

    [self.view addSubview:_label];

}

结果是这样的

方法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];

下面是效果图:

原文地址:https://www.cnblogs.com/codemakerhj/p/6611109.html