iOS 计算文本宽高

1,338 阅读1分钟

NSString

  • 固定宽度计算高度
CGFloat width = ScreenWidth - (3 * 10.0 + 55.0);
CGRect rect = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16.0]} context:NULL];
NSInteger rHeight = ceilf(rect.size.height);
NSInteger rWidth = ceilf(width);
NSLog(@"宽度 %ld 高度 %ld",(long)rWidth,(long)rHeight);
  • 由于UILabel、UITextView等有一些内边距,我在此处处理会增加一些高度
UITextView *contextView = [[UITextView alloc] initWithFrame:CGRectZero];
contextView.font = [UIFont systemFontOfSize:16.0];
contextView.textContainerInset = UIEdgeInsetsMake(5.0, 5.0, 5.0, 5.0);
contextView.editable = NO;
contextView.scrollEnabled = NO;
contextView.dataDetectorTypes = UIDataDetectorTypeAll;
contextView.backgroundColor = [UIColor systemGrayColor];
[self.view addSubview:contextView];
contextView.frame = CGRectMake(75.0, 80.0, rWidth, rHeight+10.0);
contextView.text = text;

NSMutableAttributedString

  • 计算高度
NSMutableAttributedString *firstText = [[NSMutableAttributedString alloc] initWithString:@"  昨夜风开露井桃,未央前殿月轮高。平阳歌舞新承宠,帘外春寒赐锦袍。"];
[firstText addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, firstText.length)];
[firstText addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16.0 weight:UIFontWeightMedium]} range:NSMakeRange(0, firstText.length)];
// 设置图片
NSTextAttachment *imageAttach = [[NSTextAttachment alloc] init];
imageAttach.image = [UIImage imageNamed:@"emojiImg"];
imageAttach.bounds = CGRectMake(5.0, -2.0, 15.0, 15.0);
NSAttributedString *imageAttribute = [NSAttributedString attributedStringWithAttachment:imageAttach];
NSMutableAttributedString *imageText = [[NSMutableAttributedString alloc] initWithAttributedString:imageAttribute];
[imageText appendAttributedString:firstText];

CGRect attriRect = [imageText boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:**NULL**];
NSInteger rHeight = ceilf(attriRect.size.height);
NSInteger rWidth = ceilf(width);

NSLog(@"宽度 %ld 高度 %ld",(long)rWidth,(long)rHeight);
contextView.frame = CGRectMake(75.0, 80.0, rWidth, rHeight+10.0);
contextView.attributedText = imageText;