美文网首页
ios 计算字符串高度 UILable或UITextView自适

ios 计算字符串高度 UILable或UITextView自适

作者: 木子李55 | 来源:发表于2019-12-01 00:16 被阅读0次

前言: UILable或者UITextView展示文本,当文本长度是变化时,需要我们先计算出文本的高度,再布局Frame,这样无论文本怎么变化,我们的布局大小总是合适的。

    //** 首先计算出指定宽度和大小的文本会占用的高度
    NSString *str = @"某某银行移动动瑞银行移动银行银行移银行银行移动银行银行移";
    CGRect strRect = [str boundingRectWithSize:CGSizeMake(300-16, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil];

    //** 如果是标签
    UILabel *testLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 300, strRect.size.height)];
    testLable.text = str;
    testLable.font = [UIFont systemFontOfSize:16];
    testLable.numberOfLines = 0;
    testLable.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:testLable];

    //** 如果是文本 (因为textview周边距有8,所以计算的时候宽度要减16,赋值frame的时候高度要加16)
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 100, 300, strRect.size.height+16)];
    textView.text = str;
    textView.font = [UIFont systemFontOfSize:16];
    textView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:textView];

//** 如果此外文本显示还要有字间距和行间距,则使用富文本字符串
    NSMutableAttributedString *attributedContentStr = [[NSMutableAttributedString alloc] initWithString:@"        感谢您信任并下载使用某某APP。\n        我行深知个人信息对您而言的重要性,一直采取严格的安全保护措施来保障您的个人信息安全。未经您的授权,我行不会向任何第三方提供您的个人信息。您在使用某某APP时,我行需要您授权以下协议。\n        请您在使用某某APP前认真阅读我行完整《某某APP用户隐私政策》(点击链接),并确认是否同意。如您同意,请点击“同意”开始我行的服务。" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14], NSForegroundColorAttributeName:[UIColor colorWithHex:0x999999]}];
    
    // 行间距
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:5];
    [attributedContentStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attributedContentStr.length)];

    CGRect contentRect = [attributedContentStr boundingRectWithSize:CGSizeMake(300-16, 0) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];

    UITextView *contentTextView = [[UITextView alloc] initWithFrame:CGRectMake(50, 100, 300, 50)];
    contentTextView.attributedText = attributedContentStr;
    contentTextView.backgroundColor = [UIColor whiteColor];
    contentTextView.editable = NO;
    contentTextView.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:contentTextView];

赠人玫瑰,手留余香,欢迎交流!


image.png

相关文章

网友评论

      本文标题:ios 计算字符串高度 UILable或UITextView自适

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