UICollectionView: different size items is not calculated on reused items

廉价感情. 提交于 2019-12-21 03:42:26

问题


I have a collection view with varied item sizes which i declare in

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout*)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

    FeedItem *item = [_imagesLinkArray objectAtIndex:indexPath.row];
    return CGSizeMake(250, 200*item.sizeFactor);
}

When the cell is being reused in collectionView:cellForItemAtIndexPath: the item is being rendered with the reuesed item size and not the one specified in sizeForItemAtIndexPath:.

any ideas?


回答1:


It seems that collectionView:layout:sizeForItemAtIndexPath: is called once on layout preparation, before CollectionView is rendered.

So whenever you scroll and a cell is dequeued it is resized to the size provided by collectionView:layout:sizeForItemAtIndexPath: at preparation stage. Are you expecting this method to be called whenever a cell with certain indexPath gets visible? So that you can dynamically change cell size? seems this is not how this method can be used, it can be used to determine the size of a cell once at layout preparation stage.

In case you need the sizes to be recomputed for some reason, you can invalidate the layout using [UICollectionViewLayout invalidateLayout].




回答2:


A collection view seems to recompute items less often than a UITableView. You have to inform the collection view about most of the changes to the underlying model, e.g. by calling [collectionView reloadData] or [collectionView insertItemsAtIndexPaths:indexPaths].




回答3:


You need to Override this function in custom layout class. if you are using custom layout.

override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}



回答4:


You can simple override the scroll view delegate

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    collectionView.collectionViewLayout.invalidateLayout()
}


来源:https://stackoverflow.com/questions/13318317/uicollectionview-different-size-items-is-not-calculated-on-reused-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!