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

一、因爲label控件沒有contentInsets屬性,須要自定義label,添加Insets 屬性,並重寫父類的幾個方法app

//下面四個方法用來初始化edgeInsets字體

- (instancetype)init {spa

    if (self = [super init]) {code

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

    }io

    return self;class

}方法

 

- (instancetype)initWithFrame:(CGRect)frameim

{top

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

}

 

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

相關文章
相關標籤/搜索