調用heightForRowAtIndexPath時,UITableViewCell的contentView具有不同的寬度:

[英]UITableViewCell's contentView has different width when calling in heightForRowAtIndexPath:


I am trying to calculate the height of a table view cell that is layout using auto layout. As this has to be compatible to iOS7 as well, I need to return a valid height for heightForRowAtIndexPath:.

我試圖計算使用自動布局布局的表格視圖單元格的高度。由於這也必須與iOS7兼容,我需要返回heightForRowAtIndexPath:的有效高度。

What I am doing is the following:

我正在做的是以下內容:

if (self.userRatingsAbbreviatedTextCell == nil) {
    self.userRatingsAbbreviatedTextCell = [[UserRatingsAbbreviatedTextCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
}
[self.userRatingsAbbreviatedTextCell prepareForReuse];
UserRating *rating = [self.paginationModel ratingAtIndex:reviewIndex];
[self.userRatingsAbbreviatedTextCell configureCellForHotelUserRating:rating];
[self.userRatingsAbbreviatedTextCell layoutIfNeeded];

CGSize size = [self.userRatingsAbbreviatedTextCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return size.height;

The cell has a disclosure indicator. When I ask the cell for its contentView width it is 296. However in cellForRowAtIndexPath: after dequeuing a cell, its contentView width is 289, which is the size that is used for rendering. Has anybody experienced such issues? What do I need to do for the cell to set its contentView width correctly?

該單元具有披露指標。當我向單元格詢問其contentView寬度時,它是296.但是在cellForRowAtIndexPath中:在單元格出列后,其contentView寬度為289,這是用於渲染的大小。有沒有人遇到過這樣的問題?我需要做什么才能讓單元格正確設置其contentView寬度?

1 个解决方案

#1


0  

My solution to the contentView being a different size than the UITableViewCell. May break some of UITableViewCell's innate properties such as accessory views.

我對contentView的解決方案與UITableViewCell的大小不同。可能會破壞一些UITableViewCell的固有屬性,例如附件視圖。

Override UITableViewCell's layoutSubviews method in your cell class:

覆蓋單元類中的UITableViewCell的layoutSubviews方法:

- (void)layoutSubviews
{
    [super layoutSubviews];

    // force `contentView` to be the same size as `self` (it's typically 0.5pt smaller)
    CGRect contentViewFrame = self.contentView.frame;
    contentViewFrame.size = CGSizeMake(CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
    self.contentView.frame = contentViewFrame;
}

In my case, the contentView was always 0.5 points smaller and it was causing problems when calculating the correct height for tableView:heightForRowAtIndexPath:. I would calculate the perfect height for the cell that wouldn't cause a UILabel to wrap but it would always cut off the last line since the height was 0.5 points too small.

在我的例子中,contentView總是小0.5點,並且在計算tableView的正確高度時引起問題:heightForRowAtIndexPath:。我會計算出不會導致UILabel包裹的單元格的完美高度,但是由於高度為0.5點太小,它總是會切斷最后一條線。

My cell, for reference:

我的手機,供參考:

Custom UITableViewCell XIB


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/10/30/720e88e10857ca8f377cc27620063c75.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com