美文网首页
boundingRectWithSize 宽度问题

boundingRectWithSize 宽度问题

作者: Fsn_soul | 来源:发表于2022-08-22 23:27 被阅读0次

boundingRectWithSize 指定宽度,计算高度。

NSString *text = @"收到翻到了师傅的说法,扩大说法打三等奖撒大声但是,俯瞰风景阿萨法上课地卡萨丁撒。";
//    NSString *text = @"11111111111111111111111111111111111111111111111111111111111111111"; 
    UIFont *font = [UIFont systemFontOfSize:16];
    NSAttributedString *attriText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: font}];
    
    CGRect rect = [attriText boundingRectWithSize:CGSizeMake(223, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
    NSLog(@"%@", NSStringFromCGRect(rect));
    
    CGRect rect1 = [text boundingRectWithSize:CGSizeMake(223, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: font} context:nil];
    NSLog(@"%@", NSStringFromCGRect(rect1));
    
    UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    contentLabel.font = font;
    contentLabel.text = text;
    contentLabel.numberOfLines = 0;
    contentLabel.textAlignment = NSTextAlignmentLeft;
    CGSize sizeToFit = [contentLabel sizeThatFits:CGSizeMake(223, MAXFLOAT)];
    NSLog(@"%@", NSStringFromCGSize(sizeToFit));

第一个打印:

2022-08-22 23:21:40.067382+0800 PodDemo[17825:431803] {{0, 0}, {212.15999999999997, 76.375}}
2022-08-22 23:21:40.067693+0800 PodDemo[17825:431803] {{0, 0}, {212.15999999999997, 76.375}}
2022-08-22 23:21:40.068116+0800 PodDemo[17825:431803] {212.33333333333334, 76.666666666666671}

第二个打印:

2022-08-22 23:24:34.479876+0800 PodDemo[17892:434661] {{0, 0}, {220.390625, 57.28125}}
2022-08-22 23:24:34.480291+0800 PodDemo[17892:434661] {{0, 0}, {220.390625, 57.28125}}
2022-08-22 23:24:34.480799+0800 PodDemo[17892:434661] {220.66666666666666, 57.333333333333336}

计算出来的矩形是个紧凑的矩形。并且还可以发现即使文本发生换行,它的宽度也不会等于指定的宽度,只会小于指定宽度,有时候差指定宽度10-20个pt,在UI上显示会有瑕疵,貌似没有好的解决办法,因为即时等于指定宽度,但是因为剩余的空间放不下一个字符还是会换行空出。

相关文章

网友评论

      本文标题:boundingRectWithSize 宽度问题

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