I want to set the position of my UICollectionViewCell. After doing some research on it I found a post that explains the process, however in objective-c. I believe I translated it correctly however I can't get it to work.
Here's the link to the question: How do I set the position of a UICollectionViewCell?
Here's the answer in 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;
}
}
Here's my swift version
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
}
}
}
However in layoutAttributesForElements I get an error saying indexPath is an unresolved identifier...
My VC is subclassed as the following UICollectionViewController, UICollectionViewDelegateFlowLayout, UITextViewDelegate
Any suggestions?
If you know any other methods to reposition UICollectionViewCells that'd be great also.
EDIT
I have included a screenshot.
The red rectangle is the cell. I want it to be on the gray line