我使用下面的代码计算文本的高度,然后为UILabel和UITextView设置此高度
CGSize targetSize = CGSizeMake(300,CGFLOAT_MAX); NSString *message = @"The Internet connection appears to be offline."; NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init]; CGSize boundingBox = [message boundingRectWithSize:targetSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:FontOpenSanWithSize(14)} context:context].size; CGSize size = CGSizeMake(ceil(boundingBox.width),ceil(boundingBox.height)); // it will return size:width = 299 and size height 20 // => if I use this height and set for UILabel,it can display full content // => if I use this height and set for UITextView,it can not display full content
这对于UILabel来说是完美的,但对于UITextView来说,它计算错误.
我认为问题的发生是因为UITextView的填充(左,右)比UILabel大.
那么如何计算正确的文本大小以便在UITextView中显示.任何帮助或建议将非常感谢.
如下面的描述图片
具有相同的大小(300),相同的字体,相同的文字,但UITextView显示在2行,但UILabel在1行.
我的计算高度代码返回20,不足以显示2行,因此UITextView无法显示完整内容
之所以我需要根据文本计算UITextView的高度,因为我的UITextView是一个弹出窗口.
弹出窗口高度取决于TextView高度
解决方法
您可以尝试两件事:
>设置textView.textContainerInset = UIEdgeInsetsZero
>设置textView.textContainer.lineFragmentPadding = 0
通过这些操作,您可以摆脱textView中的所有填充,当其宽度与标签的宽度匹配时,高度也是相同的.
这是一个示例代码,您可以将其放在一个空的viewController中并自己测试:
- (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; NSString *text = @"The internet connection appears to be offline."; CGFloat width = 100.f; UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20,20,width,300)]; textView.font = [UIFont fontWithName:@"AvenirNext-Regular" size:12.f]; textView.text = text; [self.view addSubview:textView]; UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20 + width,300)]; label.numberOfLines = 0; label.font = [UIFont fontWithName:@"AvenirNext-Regular" size:12.f]; label.text = text; [self.view addSubview:label]; // Getting rid of textView's padding textView.textContainerInset = UIEdgeInsetsZero; textView.textContainer.lineFragmentPadding = 0; // Setting height of textView to its contentSize.height CGRect textViewFrame = textView.frame; textViewFrame.size = textView.contentSize; textView.frame = textViewFrame; // Setting height of label accorting to it contents and width CGRect labelFrame = label.frame; labelFrame.size = [label sizeThatFits:CGSizeMake(width,HUGE_VALF)]; labelFrame.size.width = width; label.frame = labelFrame; NSLog(@"Label bounds: %@",NSStringFromCGRect(label.bounds)); NSLog(@"TextView bounds: %@",NSStringFromCGRect(textView.bounds)); // Visualizing final effect with borders textView.layer.borderColor = [UIColor redColor].CGColor; textView.layer.borderWidth = 1.f; label.layer.borderColor = [UIColor greenColor].CGColor; label.layer.borderWidth = 1.f; }
控制台输出:
2016-09-01 14:29:06.118 stack39268477[943:243243] Label bounds: {{0,0},{100,66}} 2016-09-01 14:29:06.119 stack39268477[943:243243] TextView bounds: {{0,66}}