我将一个 UILabel 子类化,我打算在许多不同UITableViewCell
的 s 中使用它。
在setText:
我曾经sizeWithFont
获得过动态高度的UILabel
.
这一切都很好,但是,子类的框架在UILabel
重绘单元格之前不会改变。我该如何克服呢?
注意:if
在下面的代码中,由于语句的原因,重绘时大小不会改变。我把它拿出来测试,发现它在重绘后有效。
我认为它需要使用setNeedsDisplay
或类似的,但它们也不起作用。
这是我正在使用的代码:
- (void)setText:(NSString *)text
{
if (text != _text) {
// Adjust size to fit contents
//
CGSize maximumSize = CGSizeMake(CGRectGetWidth(self.frame), CGFLOAT_MAX);
CGSize predictedSize = [text sizeWithFont:self.font constrainedToSize:maximumSize lineBreakMode:self.lineBreakMode];
NSLog(@"Predicted size for \"%@\" (width: %f) is %@", text, self.frame.size.width, NSStringFromCGSize(predictedSize));
CGRect headlineDescriptionLabelFrame = self.frame;
headlineDescriptionLabelFrame.size = predictedSize;
NSLog(@"Old frame: %@", NSStringFromCGRect(self.frame));
[self setFrame:headlineDescriptionLabelFrame];
NSLog(@"New frame: %@", NSStringFromCGRect(self.frame));
_text = text;
}
}
我的输出看起来像这样(上面的'if'关闭):
2012-12-19 19:51:23.576 myApp[1099:c07] Predicted size for "Facebook's photo-sharing service Instagram denies that it has changed its privacy policy to allow it to sell users' photos to advertisers." (width: 172.000000) is {170, 75}
2012-12-19 19:51:23.578 myApp[1099:c07] Old frame: {{138, 46}, {172, 49}}
2012-12-19 19:51:23.578 myApp[1099:c07] New frame: {{138, 46}, {170, 75}}
此处重新加载单元格
UILabel 已调整大小并在第一次单元格重新加载后显示
2012-12-19 19:51:30.018 myApp[1099:c07] Predicted size for "Facebook's photo-sharing service Instagram denies that it has changed its privacy policy to allow it to sell users' photos to advertisers." (width: 172.000000) is {170, 75}
2012-12-19 19:51:30.018 myApp[1099:c07] Old frame: {{138, 46}, {172, 49}}
2012-12-19 19:51:30.019 myApp[1099:c07] New frame: {{138, 46}, {170, 75}}
单元格在此处重新加载
2012-12-19 19:51:32.014 myApp[1099:c07] Predicted size for "Facebook's photo-sharing service Instagram denies that it has changed its privacy policy to allow it to sell users' photos to advertisers." (width: 170.000000) is {170, 75}
2012-12-19 19:51:32.014 myApp[1099:c07] Old frame: {{138, 46}, {170, 75}}
2012-12-19 19:51:32.015 myApp[1099:c07] New frame: {{138, 46}, {170, 75}}
编辑
经过4天的尝试,我仍然遇到这个问题,有谁知道这是否是Apple方面的错误?其他人如何调整从 UITableViewCell 笔尖加载的 UILabel 的大小cellForRowAtIndexPath:
?