UITextView sizeThatFits返回的大小与boundingRectWithSize不同 [英] UITextView sizeThatFits returns different size than boundingRectWithSize
问题描述
需要 UITextView
所需的高度。 sizeThatFits
返回更大,但正确的高度超过 boundingRectWithSize
。为什么存在差异?
Need the required height of UITextView
. sizeThatFits
returns bigger, but the correct height than boundingRectWithSize
. Why difference exist?
在两个地方我需要知道高度。在 cellForRowAtIndexPath
和 heightForRowAtIndexPath
中。
At two places I need to know the height. In cellForRowAtIndexPath
and in heightForRowAtIndexPath
.
我不认为在 heightForRowAtIndexPath中始终创建一个
只知道需要什么样的高度。 UITextView
是有效的
I do not think it is efficient to create always a UITextView
in heightForRowAtIndexPath
just to know what height is required.
你知道计算 UITextView $ c $高度的方法吗? c>在
heightForRowAtIndexPath
?
推荐答案
我上个月遇到了类似问题UITableView,我使用boundingRectWithSize来计算大小,它实际上是正确的。然后我将它放入UITextView。
I met similar problem last month for UITableView, and I use boundingRectWithSize to calculate the size, it is actually correct. I then put it into UITextView.
我犯了一些错误:
- I忘记在计算时设置相同的字体大小和UITextView
- UITextView有边距,我会手动将它添加到heightForRowAtIndexPath并将textContainerInset设置为相同的。
希望它可以帮到你。
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger section = indexPath.section;
NSUInteger axisIndex = section - 2;
yAxis *yAxisObj = self.yAxisInfoArray[axisIndex];
boundingRect = [yAxisObj.yAxisDescription boundingRectWithSize:CGSizeMake(self.descriptionViewWidth, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
attributes:@{NSFontAttributeName:self.contentFont}
context:nil];
return boundingRect.size.height + TEXT_TOP_MARGIN + TEXT_BOTTOM_MARGIN;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellId = @"ChartDescriptionCell";
ChartDescriptionCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
if (!cell) {
cell = [[ChartDescriptionCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
cell.textView.bounces = NO;
cell.textView.showsHorizontalScrollIndicator = NO;
cell.textView.showsVerticalScrollIndicator = NO;
cell.textView.font = self.contentFont;
cell.textView.textColor = [UIColor colorWithHex:@"#333333"];
cell.textView.textContainerInset = UIEdgeInsetsMake(TEXT_TOP_MARGIN, -5, TEXT_BOTTOM_MARGIN, -5);
}
NSInteger section = indexPath.section;
NSUInteger axisIndex = section - 2;
yAxis *yAxisObj = self.yAxisInfoArray[axisIndex];
cell.textView.text = yAxisObj.yAxisDescription;
}
return cell;
}
这篇关于UITextView sizeThatFits返回的大小与boundingRectWithSize不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!