IOS 7 incorrect calculation of UITableViewCell height on first pass

I am trying to calculate the height of my uitableviewcell subclass in iOS 7 and I find the calculation is wrong on the first pass. However, if I reload the table view after a second, the calculation is indeed correct on the second pass. This is how I calculate the height of a cell:

    if (_prototypeHeader == nil) {
            _prototypeHeader = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([DDStatusTableViewCell class]) owner:nil options:0] lastObject];
    }
    [_prototypeHeader setFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 0)];
    [_prototypeHeader configureForMenu:self.menu atRestaurant:self.restaurant];
    [_prototypeHeader setNeedsLayout];
    [_prototypeHeader layoutIfNeeded];

    CGSize size = [_prototypeHeader.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    NSLog(NSStringFromCGSize(size));
    return size.height + 1;

      

The log statement logs this for size:

2014-10-28 10:15:45.492 MyApp[39252:613] {350, 77} <--- this is incorrect
2014-10-28 10:15:46.495 MyApp[39252:613] {294, 110} <--- this is correct

      

I also crossed out the table width in both circumstances and it seems to be consistent 320. This is only a problem in iOS 7. What gives?

Thank!

EDIT

After further checking, I determined that the layout width of my top label was not correct. In the layoutsubviews label method, I do the following:

- (void)layoutSubviews {
    [super layoutSubviews];
    self.titleLabel.preferredMaxLayoutWidth = self.titleLabel.frame.size.width;
    self.detailLabel.preferredMaxLayoutWidth = self.detailLabel.frame.size.width;
    [super layoutSubviews];
}

      

In the first pass, the width of the titleLabel is 170, and in the second pass, the width is 130. Still trying to figure out why. The contentView's width is also 360 during the first pass, and shrinks to 320 for the second pass. It seems that the layout code that adjusts the width of the label happens before the contentView is resized.

+3


source to share


1 answer


requesting a cell to lay out the contentView before changing the preferredMaxLayoutWidth seems to do the trick.



- (void)layoutSubviews {
    [super layoutSubviews];
    [self.contentView layoutIfNeeded];
    self.titleLabel.preferredMaxLayoutWidth = self.titleLabel.frame.size.width;
    self.detailLabel.preferredMaxLayoutWidth = self.detailLabel.frame.size.width;
    [super layoutSubviews];
} 

      

+3


source







All Articles