我想设置我的UICollectionViewCell的位置。在对它进行了一些研究之后,我发现了一篇解释过程的文章,但是在Objective-C中。我相信我正确地翻译了它,但是我无法使它正常工作。重新定位UICollectionViewCells?
这里的链接的问题: How do I set the position of a UICollectionViewCell?
下面是Objective-C的答案
- (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];
}
}
- (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;
}
}
这里是我的SWIFT版本
func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if (indexPath.section == 0 && indexPath.item == 1) {
let layoutAttributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
layoutAttributes.frame = CGRect(x: 0, y: 0, width: 20, height: 50)
return layoutAttributes
}
else
{
}
return layoutAttributesForItem(at:indexPath)
}
func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let layoutAttributes = layoutAttributesForElements(in: rect)! as NSArray
func contains(_ rect2: CGRect) -> Bool {
if rect2 == CGRect(x: 0, y: 0, width: 2, height: 50) {
let layoutAttributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
layoutAttributes.frame = CGRect(x: 0, y: 0, width: 20, height: 50) // or whatever...
return layoutAttributes
}
else{
return layoutAttributes
}
}
}
然而,在layoutAttributesForElements我得到一个错误说indexPath是一个无法识别的标识符...
我的VC的子类,如下 UICollectionViewController,UICollectionViewDelegateFlowLayout,UITextViewDelegate
有什么建议?
如果您知道任何其他重新定位UICollectionViewCells的方法,那也会很棒。
编辑
我已经包含了一个屏幕截图。
你是什么意思,我的集合视图单元格的位置?你想让你的单元表现得如何?你想在收集视图内插入单元格吗?你想以特定的方式调整单元格大小吗?多一点上下文会有帮助,因为你的问题不容易从你的代码中推演出来。 –
@EliWhittle我知道我可以使用插入,但这似乎是一个不正当的工作。我希望细胞出现在某个地方以回应通知。我甚至不知道是否可以对细胞进行动画处理,所以我只是想把它放在一个地方,然后改变它的背景色来清除。这是因为我打算在单元格内放置一个UICollectionView。这是最终目标。位于视图下半部分的UICollectionViewCell中的UICollectionView。希望有所帮助。 – Stefan
你有没有想要达到的目标,我很难想象你的问题。 –