使用SizeWithFont计算NSString的大小时的计算错误:CondectaintaintedTosize:LineBreakMode
-
25-10-2019 - |
题
我有一个由UITEXTVIEW组成的子视图。文本视图的内容是动态的,因此我想测量确切的宽度和高度,以创建一个单元格和一个文本视图,而无需滚动。
我创建了以下方法来衡量NSString将需要的大小:
- (CGSize)getSizeOfString:(NSString *)str font:(NSString *)theFont fontSize:(CGFloat)theSize {
CGSize maxSize = CGSizeMake(280, CGFLOAT_MAX);
UIFont *font = [UIFont fontWithName:theFont size:theSize];
return [str sizeWithFont:font constrainedToSize:maxSize lineBreakMode:UILineBreakModeWordWrap];
}
我以这种方式使用它:
// CellForRowAtIndexPath
.....
CGSize size = [strTool getSizeOfString:text font:TEXT_FONT fontSize:TEXT_SIZE];
CGFloat width = size.width;
CGFloat height = size.height;
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(15, 10, width, height)];
[textView setBackgroundColor:[UIColor blueColor]];
textView.font = [UIFont fontWithName:TEXT_FONT size:TEXT_SIZE];
textView.editable = NO;
// Set value
textView.text = text;
[cell.contentView addSubview:textView];
[textView release];
return cell;
// heightForRowAtIndexPath
NSString *returnStr;
if (indexPath.section == SECTION_SHORT)
returnStr = self.manchet;
else
returnStr = self.newsText;
return [strTool getSizeOfString:returnStr font:TEXT_FONT fontSize:TEXT_SIZE].height;
但是,无论计算的高度太小,都会导致细胞视图内部令人讨厌的滚动。值得一提的是,几乎所有文本都包含线路破裂( n)。
我在这里做错了什么?
谢谢
解决方案
我认为您的** height forrowatIndExpath **应该看起来像这样:
NSString *returnStr;
if (indexPath.section == SECTION_SHORT) returnStr = self.manchet;
else returnStr = self.newsText;
return [strTool getSizeOfString:returnStr font:TEXT_FONT
fontSize:TEXT_SIZE].height+10.0f*2.0f;
而且,您还应该考虑到沿X沿X的文本字段15PX的偏移(这意味着SizeWithFont的宽度应在15px上较小)和从顶部的10px缩小,我建议使用相同的值对底部进行相同的值,以使其看起来为中心。
ContentView也有保证金,请考虑所有这些。
其他提示
UitextView需要比计算大小的更大空间。由于它具有最高的边距和底部边距,因此我不确定那是多少。如果您想完美合适,请尝试
nsstring drawinrect:withfont:
或者只是为UitextView提供更多空间,您可以通过尝试找到额外的空间。
不隶属于 StackOverflow