7

我想我找到了 sizeWithFont:constrainedToSize: 的边缘情况:在视网膜显示器上,它有时(它似乎基于自动换行)返回的高度比实际需要的高 1 行,而且比它实际绘制的更重要.

注意:我使用的真实代码隐藏在以性能为中心的手绘可变高度表视图单元代码中,因此我已将问题提炼为尽可能简单的示例代码。(尝试回答我的问题以外的问题时请注意这一点:-)

此示例 UIView 填充其内容,测量文本以适应(包装),填充该矩形,然后绘制文本。

在视网膜设备(或模拟器)上,返回的高度太高了 1 行,但在预视网膜设备(或模拟器)上,它返回正确的高度。

我将非常感谢任何人可能拥有的任何见解,因为这是我想修复的错误!

非常感谢!

-埃里克

- (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%3A34%3A34.png http://files.droplr.com/files/ 9979822/YpCM.Screen%20shot%202011-01-11%20at%2012%3A36%3A47.png

4

3 回答 3

2

这似乎是您的模拟器的问题。这是我在 OS 4.3.2 上使用 Retina 模拟器运行它时得到的

在此处输入图像描述

于 2011-12-02T09:03:43.987 回答
1

以下是我用来查找动态文本内容标签高度的方法。这在我的应用程序中运行良好


- (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;
}

于 2011-12-02T08:58:46.400 回答
0
        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;
于 2012-03-19T10:15:20.157 回答