Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift, Change width of UICollectionViewCell and UILabel(inside the cell) programmatically

I've set the width of a cell(UICollectionViewCell) to be equal to the width of the UICollectionView and I'm trying to do exactly the same thing with the UILabel that is included inside that cell. I think the code below explains exactly what I'm trying to achieve. So i've read some question here in SO and also a couple of tutorials but I'm still not sure how I can achieve this.

In a couple of questions it was saying about using collectionViewLayout but I'm really struggling on how to use it within my code. Any ideas? Thank you!

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("myCell", forIndexPath: indexPath) as LocationViewCell
    cell.locationLabel.text = "Hello there!"

    // Set cell & label width to 100%
    let collectionViewWidth = self.collectionView.bounds.size.width
    cell.frame.size.width = collectionViewWidth // Works
    cell.locationLabel.frame.size.width = collectionViewWidth // Does NOT 

Update 1

So I added the following:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    // Set cell width to 100%
    let collectionViewWidth = self.collectionView.bounds.size.width
    return CGSize(width: collectionViewWidth, height: 35)
}

What happens is that when the view is loaded the UILabel's width is still small. If I go to another view and then return back then it's 100%. So I have to do something in the viewDidLoad() right? I'm already using self.collectionView.reloadData() but I guess that's only for data.

Update 2

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("locationCell", forIndexPath: indexPath) as LocationViewCell
    cell.locationLabel.text = "Hello UILabel"

    // Set cell width to 100%
    let collectionViewWidth = self.collectionView.bounds.size.width
    cell.frame.size.width = collectionViewWidth
    cell.locationLabel.frame.size.width = collectionViewWidth

    return cell
}
like image 762
manosim Avatar asked Dec 28 '14 15:12

manosim


1 Answers

It doesn't work because by the time this method is called, the collection view already knows how big the cell should be because it has got it from the flow delegate method:

optional func collectionView(_ collectionView: UICollectionView,
                  layout collectionViewLayout: UICollectionViewLayout,
             sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize

This is where you should be setting the size of your cells.

like image 123
Abizern Avatar answered Oct 30 '22 23:10

Abizern