美文网首页
计算label的高度,总是忘记方法名字

计算label的高度,总是忘记方法名字

作者: 请叫我魔法师 | 来源:发表于2017-06-26 16:16 被阅读0次

    0.添加个lab:

    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 200, 20)];
    lab.text = @"左间距,上间距有效,貌似右间距没用。原本以为和contentSize有关,调了也没用。这一点还不太清楚。PS:上间距会根据文字内容多少和UITextView的高度来判断是否取消。所以最好还是设contentInset的时候就把上间距搞掉。";
    lab.numberOfLines = 0;
    lab.backgroundColor = [UIColor greenColor];
    lab.font = [UIFont systemFontOfSize:15];
    lab.textColor = [UIColor blackColor];
    [self.view addSubview:lab];
    

    1.普通的lab,就是根据字体大小,计算高度

    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:15]};//
    CGSize size = [lab.text boundingRectWithSize:CGSizeMake(200, MAXFLOAT) options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    lab.frame = CGRectMake(20, 100, 200, size.height);
    
    1.1.png

    2.设置的lab需要设置行间距、字体、字体颜色啥的,就成富文本了。

    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 10;
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:15],
                            NSParagraphStyleAttributeName : style, //行间距
                            NSKernAttributeName : @5};//字间距   
    CGSize size = [lab.text boundingRectWithSize:CGSizeMake(200, MAXFLOAT) options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;    
    NSMutableAttributedString *attS = [[NSMutableAttributedString alloc] initWithString:lab.text attributes:dic];
    lab.attributedText = attS;
    lab.frame = CGRectMake(20, 100, 200, size.height);
    
    2.2.png

    相关文章

      网友评论

          本文标题:计算label的高度,总是忘记方法名字

          本文链接:https://www.haomeiwen.com/subject/notkcxtx.html