NSString SizeWithFont:约束:返回视网膜显示器上的不正确高度
-
10-10-2019 - |
题
我想我已经找到了一个sizewithfont的边缘案例:约束:在视网膜显示器上,它有时会(似乎是基于单词包装)返回高度1线比实际需要的高,而且比实际绘制更重要的是。
注意:我正在使用的真实代码被埋葬在表演者中心绘制的可变高度表查看单元格中,因此我将问题提炼为尽可能简单的示例代码。 (当试图回答我的问题以外的其他问题时,请注意这一点:-)
该示例uiview填充了它的内容,测量要适合(包装)的文本,填充了式,然后绘制文本。
在视网膜设备(或模拟器)上,返回高度的高度太高,但是在预雷纳设备(或模拟器)上,它返回正确的高度。
我非常感谢任何人可能拥有的任何见解,因为这是我想解决的错误!
非常感谢!
-eric
- (void)drawRect:(CGRect)rect {
NSString * theString = @"Lorem ipsum dolor sit ameyyet, consectetur adipiscing elit. Etiam vel justo leo. Curabitur porta, elit vel.";
UIFont * theFont = [UIFont systemFontOfSize:12];
CGSize theConstraint = CGSizeMake(rect.size.width - 20, rect.size.height - 20);
CGSize theResultSize = [theString sizeWithFont:theFont constrainedToSize:theConstraint];
// dump the measurements
NSLog(@"returned a size h = %f, w = %f", theResultSize.height, theResultSize.width);
// fill the whole rect
CGContextRef context = UIGraphicsGetCurrentContext();
[[UIColor yellowColor] set];
CGContextFillRect(context, rect);
// fill the measured rect
CGRect theRect = CGRectMake(10, 10, theResultSize.width, theResultSize.height);
context = UIGraphicsGetCurrentContext();
[[UIColor cyanColor] set];
CGContextFillRect(context, theRect);
// draw the text
[[UIColor blackColor] set];
[theString drawInRect:theRect withFont:theFont];
}
整个简单项目可用 这里.
模拟器图像:
http://files.droplr.com/files/9979822/aldj.screen%20shot%202011-01-11%20AT%2012%2012%3A34%3A3a34.png
http://files.droplr.com/files/9979822/ypcm.screen%20shot%202011-01-11%20AT%2012%3A36%3A47.png
解决方案
您的模拟器似乎是一个问题。这就是我在操作系统4.3.2上使用视网膜模拟器运行它时得到的
其他提示
以下是我使用的方法来找到动态文本内容的标签高度。这在我的应用程序中正常工作
- (float)getHeightFortheDynamicLabel:(NSString *)stringForTheLabel
{
UITextView *aSampleTextView;
// 30 is the minimum height
aSampleTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, mywidth, 30)];
aSampleTextView.text = stringForTheLabel;
aSampleTextView.font = [UIFont systemFontOfSize:kMyFontSize];
aSampleTextView.alpha = 0;
[self.view addSubview:aSampleTextView];
float textViewHeight = aSampleTextView.contentSize.height;
[aSampleTextView removeFromSuperview];
[aSampleTextView release];
return textViewHeight;
}
NSString *strSubstring = @"asdfghjklasdfghjkl adsds";
CGFloat maxWidth = 205.0;
CGFloat maxHeight = 9999;
CGSize maximumLabelSize = CGSizeMake(maxWidth,maxHeight);
CGSize expectedLabelSize = [strSubstring sizeWithFont:[UIFont fontWithName:@"StagSans-Light" size:12] constrainedToSize:maximumLabelSize lineBreakMode:UILineBreakModeWordWrap];
NSLog(@"returned a size h = %f, w = %f", expectedLabelSize.height, expectedLabelSize.width);
return expectedLabelSize;
不隶属于 StackOverflow