UILabel实现上下左右内边距和自适用高度的计算三种方法

本文介绍了如何通过自定义UILabel实现上下左右内边距,并提供了三种计算自适应高度的方法,包括调整字体大小以适应宽度、废弃的API以及使用boundingRectWithSize方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、由于label控件没有contentInsets属性,需要自定义label,添加Insets 属性,并重写父类的几个方法

//下面四个方法用来初始化edgeInsets

- (instancetype)init {

    if (self = [super init]) {

        self.edgeInsets = UIEdgeInsetsMake(10, 0, 10, 0);

    }

    return self;

}

 

- (instancetype)initWithFrame:(CGRect)frame

{

    if(self = [super initWithFrame:frame])

    {

        self.edgeInsets = UIEdgeInsetsMake(10, 0, 10, 0);

    }

    return self;

}

 

//storyboard使用

- (instancetype)initWithCoder:(NSCoder *)aDecoder

{

    if (self = [super initWithCoder:aDecoder]) {

        self.edgeInsets = UIEdgeInsetsMake(10, 0, 10, 0);

    }

    return self;

}

//xib使用

- (void)awakeFromNib

{

    [super awakeFromNib];

    self.edgeInsets = UIEdgeInsetsMake(10, 0, 10, 0);

}

 

// 修改绘制文字的区域,edgeInsets增加bounds

-(CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines

{

 

  //设置第一行和最后一行距离label的距离

    CGRect rect = [super textRectForBounds:UIEdgeInsetsInsetRect(bounds,self.edgeInsets) limitedToNumberOfLines:numberOfLines];

    //根据edgeInsets,修改绘制文字的bounds

    rect.origin.x -= self.edgeInsets.left;

    rect.origin.y -= self.edgeInsets.top;

    rect.size.width += self.edgeInsets.left + self.edgeInsets.right;

    rect.size.height += self.edgeInsets.top + self.edgeInsets.bottom;

    return rect;

}

 

//绘制文字

- (void)drawTextInRect:(CGRect)rect

{

    //令绘制区域为原始区域,增加的内边距区域不绘制

    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];

}

 

2、label控件显示多行文本,需要设置numberOfLines设置为0,还要自适用高度

  //第一种方法:

  self.label.adjustsFontSizeToFitWidth=YES;

    

   //第二种方法:(废弃API)

   CGFloat fontSizeToFits;

   [self.label.text sizeWithFont:self.label.font minFontSize:12.0 actualFontSize:&fontSizeToFits forWidth:self.label.bounds.size.width lineBreakMode:NSLineBreakByWordWrapping];//12是最小字体

    self.label.font = [self.label.font fontWithSize:fontSizeToFits];

    

  //第三种方法:

  CGSize labelSize = [self.text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 20, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil].size;

  self.label.frame = CGRectMake(0, 0, labelSize.width, labelSize.height);

 

转载于:https://www.cnblogs.com/yuhao309/p/9497387.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值