• Objective-C学习-UILabel的使用


    label.adjustsFontSizeToFitWidth = YES;  让字体自适应label

    label.numberOfLines = [label.text length];  竖向显示文本

    UILabel 高度根据内容多少来改变

    1.新建类别
    UILabel+BoundingRect.h 

    #import

    @interface UILabel (BoundingRect)

    //初始化的size,size中高度或者宽度为0

    -(CGRect)boundingRectWithInitSize:(CGSize)size;

    @end

    UILabel+BoundingRect.m

    #import "UILabel+BoundingRect.h"

    @implementation UILabel (BoundingRect)

    -(CGRect)boundingRectWithInitSize:(CGSize)size

    {

      

        self.lineBreakMode=NSLineBreakByWordWrapping;

        

        CGRect rect=[self.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:self.font,NSFontAttributeName, nil] context:nil];

        

        return rect;

    }

    @end

     

     //给定宽度,要知道label的高度

        self.label=[[UILabel alloc]initWithFrame:CGRectMake(100, 100, 200, 0)];

        self.label.font=[UIFont fontWithName:@"HelveticaNeue" size:18.0f];

        self.label.text=@"潇洒哥:最近怎样?在那里呆的还习惯吗?哪天聚一聚,一起吃顿饭";

        self.label.textColor=[UIColor darkGrayColor];

        [self.view addSubview:self.label];

        

        self.label.numberOfLines=0; //PS:这句很主要,否则默认行数为1,只显示一行文字后面截断了就没有了

        CGRect myRect=[self.label boundingRectWithInitSize:self.label.frame.size];

        self.label.frame=CGRectMake(100, 100, 200, myRect.size.height+100);

     

    反之,也可以固定高度,来确定label的宽度。

     
    boundingRect求出的高度总是为0,
    原因没有设置好text font (或者没有固定宽度)
    text font 一定要在boundingRect方法前设置好
     

     

    在UILabel显示不同的字体和颜色

    UILabel *matchScoreLabel = [[UILabel alloc] initWithFrame:...];

    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Using NSAttributed String"];

        [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,4)];

        [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(6,12)];

        [str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(19,6)];

        [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:30.0] range:NSMakeRange(0, 5)];

        [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:30.0] range:NSMakeRange(6, 12)];

        [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:30.0] range:NSMakeRange(19, 6)];

    matchScoreLabel.attributedText = str;

    本内容来自: 超越昨天(学无止境) - http://www.cnblogs.com/xvewuzhijing/
  • 相关阅读:
    算法--判断数组中是否有重复值
    算法--小范围排序
    Spark性能调优之JVM调优
    算法-java代码实现基数排序
    算法-java代码实现计数排序
    算法-java代码实现希尔排序
    算法-java代码实现堆排序
    Kafka集群的搭建
    深度学习必备包
    Keras 学习之旅(一)
  • 原文地址:https://www.cnblogs.com/xvewuzhijing/p/4901542.html
Copyright © 2020-2023  润新知