简体   繁体   中英

How to get correct width of a UIView inside UITableViewCell?

I added a UICollectionView inside UITableViewCell. I am trying to set the collectionView.collectionViewLayout.itemSize.width equal to a UIView pageContainerView.bound.size.width inside table view cell. I am trying to set the item size in awakeFromNib . The pageContainerView is added using autolayout, it has both 8 leading and trailing to the super view.

- (void)awakeFromNib {
    [super awakeFromNib];

    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    CGFloat width = self.pageContainerView.bounds.size.width;
    CGSize size = CGSizeMake(width, 321);
    layout.itemSize = size;
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
}

But the item size width is shorter than its expected.

I believe the issue here is that you are setting the size of the cell before it is actually displayed on the screen, therefore the whole cell isn't actually the size of the screen yet. I would try setting the cell size when you configure the cell (in cellForItemAt).

You can get the correct size in layoutSubviews

- (void) layoutSubviews {
    [super layoutSubviews];
    CGFloat width = self.pageContainerView.bounds.size.width;
    CGSize size = CGSizeMake(width, 321);
    self.layout.itemSize = size;
    [self.layout invalidateLayout];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM