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

     

  • 相关阅读:
    Gitblit搭建及Git协作开发流程
    Windows平台使用Gitblit搭建Git服务器图文教程
    gitblit搭建git服务器
    IntelliJ IDEA手动配置连接MySQL数据库
    如何去掉Intellij IDEA过多的警告 设置警告级别
    修改和重置WAMP的phpMyAdmin密码
    phpMyAdmin中config.inc.php设置密码和修改密码的方法
    Oracle、Mysql、SqlServer创建表和给表和字段加注释
    java注释规范
    JAVA基础补漏--static
  • 原文地址:https://www.cnblogs.com/yuhao309/p/9497387.html
Copyright © 2011-2022 走看看