iOS label 左上对齐

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

1.  sizeToFit 先定义一个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];

}

结果是这样的


然后在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.重写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];


下面是效果图:



暂时只总结了这三种方法,希望大家多多交流。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值