ios – UICollectionViewLayout layoutAttributesForElementsInRect和layoutAttributesForItemAtIndexPath

前端之家收集整理的这篇文章主要介绍了ios – UICollectionViewLayout layoutAttributesForElementsInRect和layoutAttributesForItemAtIndexPath前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在实现自定义流布局.它有两种主要的重写方法来确定单元格的布局:layoutAttributesForElementsInRect和layoutAttributesForItemAtIndexPath.

在我的代码中,调用layoutAttributesForElementsInRect,但是layoutAttributesForItemAtIndexPath不是.什么决定哪个被叫? layoutAttributesForItemAtIndexPath在哪里被调用

解决方法

layoutAttributesForElementsInRect:不一定调用layoutAttributesForItemAtIndexPath :.

实际上,如果你的UICollectionViewFlowLayout子类化,流布局将准备布局并缓存生成属性.所以当layoutAttributesForElementsInRect:被调用时,它不会要求layoutAttributesForItemAtIndexPath:,而只是使用缓存的值.

如果要确保布局属性总是根据布局进行修改,请为layoutAttributesForElementsInRect:和layoutAttributesForItemAtIndexPath ::实现一个修饰符

  1. - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
  2. {
  3. NSArray *attributesInRect = [super layoutAttributesForElementsInRect:rect];
  4. for (UICollectionViewLayoutAttributes *cellAttributes in attributesInRect) {
  5. [self modifyLayoutAttributes:cellAttributes];
  6. }
  7. return attributesInRect;
  8. }
  9.  
  10. - (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
  11. {
  12. UICollectionViewLayoutAttributes *attributes = [super layoutAttributesForItemAtIndexPath:indexPath];
  13. [self modifyLayoutAttributes:attributes];
  14. return attributes;
  15. }
  16.  
  17. - (void)modifyLayoutAttributes:(UICollectionViewLayoutAttributes *)attributes
  18. {
  19. // Adjust the standard properties size,center,transform etc.
  20. // Or subclass UICollectionViewLayoutAttributes and add additional attributes.
  21. // Note,that a subclass will require you to override copyWithZone and isEqual.
  22. // And you'll need to tell your layout to use your subclass in +(Class)layoutAttributesClass
  23. }

猜你在找的iOS相关文章