更新setText中的子类UILabel帧:因为UILabel在UITableViewCell中不会调整大小,直到重新加载单元格为止

时间:2012-12-19 19:52:56

标签: ios uilabel frame sizewithfont

我已将UILabel子类化,我打算在许多不同的UITableViewCell内使用。

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天的努力弄明白,我仍然遇到这个问题,有人知道这是苹果方面的错误吗?其他人如何调整从cellForRowAtIndexPath:内的UITableViewCell笔尖加载的UILabel?

2 个答案:

答案 0 :(得分:0)

请尝试

,而不是“在此处重新加载单元格”
[tableView beginUpdates];
[tableView endUpdates];

触发重新计算。没有真正重新加载它们的单元格高度,这是不必要的,因为你只更改了标签的文本。

答案 1 :(得分:0)

事实证明,我需要做的就是将帧更改代码添加到layoutSubviews(以及超级方法[super layoutSubviews]