UILabel實現上下左右內邊距和自適用高度的計算三種方法


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);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM