桥边风满袖
实践出真知,勤奋则必达!

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

 

posted on 2018-08-18 15:12  桥边风满袖  阅读(4034)  评论(0编辑  收藏  举报