UICollectionViewLayout layoutAttributesForElementsInRect 和 layoutAttributesForItemAtIndexPath [英] UICollectionViewLayout layoutAttributesForElementsInRect and layoutAttributesForItemAtIndexPath

本文介绍了UICollectionViewLayout layoutAttributesForElementsInRect 和 layoutAttributesForItemAtIndexPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实施自定义流程布局.它有 2 种主要的重写方法来确定单元格的位置:layoutAttributesForElementsInRectlayoutAttributesForItemAtIndexPath.

I'm implementing a custom flow layout. It has 2 main methods for overriding to determine placement of cells: layoutAttributesForElementsInRect and layoutAttributesForItemAtIndexPath.

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

In my code, layoutAttributesForElementsInRect is called, but layoutAttributesForItemAtIndexPath isn't. What determines which gets called? Where does layoutAttributesForItemAtIndexPath get called?

推荐答案

layoutAttributesForElementsInRect: 不一定要调用 layoutAttributesForItemAtIndexPath:.

事实上,如果你继承UICollectionViewFlowLayout,流布局会准备布局并缓存结果属性.所以,当调用 layoutAttributesForElementsInRect: 时,它不会询问 layoutAttributesForItemAtIndexPath:,而只是使用缓存的值.

In fact, if you subclass UICollectionViewFlowLayout, the flow layout will prepare the layout and cache the resulting attributes. So, when layoutAttributesForElementsInRect: is called, it won't ask layoutAttributesForItemAtIndexPath:, but just uses the cached values.

如果要确保始终根据您的布局修改布局属性,请为 layoutAttributesForElementsInRect:layoutAttributesForItemAtIndexPath::

If you want to ensure that the layout attributes are always modified according to your layout, implement a modifier for both layoutAttributesForElementsInRect: and layoutAttributesForItemAtIndexPath::

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
  NSArray *attributesInRect = [super layoutAttributesForElementsInRect:rect];
  for (UICollectionViewLayoutAttributes *cellAttributes in attributesInRect) {
    [self modifyLayoutAttributes:cellAttributes];
  }
  return attributesInRect;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
  UICollectionViewLayoutAttributes *attributes = [super layoutAttributesForItemAtIndexPath:indexPath];
  [self modifyLayoutAttributes:attributes];
  return attributes;
}

- (void)modifyLayoutAttributes:(UICollectionViewLayoutAttributes *)attributes
{
  // Adjust the standard properties size, center, transform etc.
  // Or subclass UICollectionViewLayoutAttributes and add additional attributes.
  // Note, that a subclass will require you to override copyWithZone and isEqual.
  // And you'll need to tell your layout to use your subclass in +(Class)layoutAttributesClass
}

这篇关于UICollectionViewLayout layoutAttributesForElementsInRect 和 layoutAttributesForItemAtIndexPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆