zoukankan      html  css  js  c++  java
  • 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);

     

  • 相关阅读:
    读取手机联络人实例
    MotionEvent中getX()和getRawX()的区别
    Android开源项目发现--- 效率开发工具篇(持续更新)
    开发资源收藏
    ViewHolder VS HolderView ?
    如何测试 Android 中的定时事件
    性能优化实例
    lamba
    并行操作多个序列map
    连续处理函数reduce
  • 原文地址:https://www.cnblogs.com/yuhao309/p/9497387.html
Copyright © 2011-2022 走看看