user7832515
user7832515

Reputation:

How to get CollectionViewCell in collectionViewLayout?

below is my code.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell : UniversalNewChatUsersCell = collectionView.dequeueReusableCell(withReuseIdentifier: "UniversalNewChatUsersCell", for: indexPath) as! UniversalNewChatUsersCell

        cell.lblUsername.text = self.arrSelectedUsersToChat.object(at: indexPath.row) as? String

        cell.layoutSubviews()
        return cell
    }

and i want to change cell width as per it's content and for that i used below method.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 150.0, height: 44.0)
    }

currently i pass static width. now i want is that i want to access cell in collectionViewLayout method so i can get cell label and based on this label i can calculate width of it. how can i do that?

Upvotes: 0

Views: 1058

Answers (2)

Sagar Chauhan
Sagar Chauhan

Reputation: 5823

You can get cell by calling cellForItem of collectionview. Write the code in sizeForItemAt method

if let collectionViewCell = collectionView.cellForItem(at: indexPath) as? YourCollectionViewCell {
}

Upvotes: 1

Girish Chovatiya
Girish Chovatiya

Reputation: 195

Do following in collectionViewLayout method:

if let myCell = collectionView.cellForItem(at: indexPath) as? UniversalNewChatUsersCell             
    print(myCell)
}

Upvotes: 0

Related Questions