如何设置UICollectionViewCell的位置? [英] How do I set the position of a UICollectionViewCell?
问题描述
据我所知,协议方法:
(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
自动设置我创建的单元格的边界。这对于我的 UICollectionViewCells
来说都是好的,但我需要其中一个在我指定的位置。任何指针在正确的方向将不胜感激。
Automatically sets the bounds of the cell I created. This is all fine and dandy for my of the UICollectionViewCells
, but I need one of them to be in a location that I specify. Any pointers in the right direction would be appreciated.
推荐答案
我可以假设你也使用 UICollectionViewFlowLayout
如果是这样,快速和脏的答案是子类 UICollectionViewFlowLayout
,并覆盖 -layoutAttributesForItemAtIndexPath:
方法:
If so, the quick and dirty answer is to subclass UICollectionViewFlowLayout
and override the -layoutAttributesForItemAtIndexPath:
method:
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0 && indexPath.item == 2) // or whatever specific item you're trying to override
{
UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
layoutAttributes.frame = CGRectMake(0,0,100,100); // or whatever...
return layoutAttributes;
}
else
{
return [super layoutAttributesForItemAtIndexPath:indexPath];
}
}
您可能还需要覆盖 -layoutAttributesForElementsInRect:
:
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray *layoutAttributes = [super layoutAttributesForElementInRect:rect];
if (CGRectContainsRect(rect, CGRectMake(0, 0, 100, 100))) // replace this CGRectMake with the custom frame of your cell...
{
UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
layoutAttributes.frame = CGRectMake(0,0,100,100); // or whatever...
return [layoutAttributes arrayByAddingObject:layoutAttributes];
}
else
{
return layoutAttributes;
}
}
然后使用您的新子类代替 UICollectionViewFlowLayout
。
Then use your new subclass in place of UICollectionViewFlowLayout
when you create your collection view.
这篇关于如何设置UICollectionViewCell的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!