-1

I have been stuck on this problem for weeks. I am trying to design collectionview where an even cell has label on left side and odd cell has label on right side. Initially the design is ok and code runs fine but when user starts scrolling the indexPath changes and hence the label isn't aligned as wanted. The picture shows an simple desired layout. Anyone know a solution to this??

The desired UI:

Here's the link to the desired output

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • 4
    You should [edit] your question to include all relevant code in the form of a [mcve]. – Dávid Pásztor May 28 '18 at 14:40
  • 1
    Please provide code so that we can help. The answer is to: 1) adjust each cell correctly in the `cellForItemAtIndexPath:` method, 2) reset each cell in the `prepareForReuse` method. – JaredH May 28 '18 at 14:59

1 Answers1

0

You could do this in your UICollectionViewDataSource methods.

But I'd say the easiest way to do this is inside the cell's apply(_ layoutAttributes:) method.

Just create a cell subclass and override that method like so:

class MyCollectionViewCell: UICollectionViewCell {
    var myLabel: UILabel!

    override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
        super.apply(layoutAttributes)

        let isEven = layoutAttributes.indexPath.row % 2 == 0

        if isEven {
            self.myLabel.textAlignment = .right
        } else {
            self.myLabel.textAlignment = .left
        }
    }
}
ABeard89
  • 911
  • 9
  • 17