I have one collectionview and a cell inside that which is having a fixed width and dynamic height based on its contents.I am using autolayout constraints , my code is below.
I have already tried to set all types of auto constraints inside the cell and inside the view .
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ViewControllerCell
cell.lbl_text.text = "djs sdfs sdfs dsfsfd gdgfd dfgd df "
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if let flowLayout = coll_main?.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
}
In cell class method:
override func awakeFromNib() {
super.awakeFromNib()
self.contentView.autoresizingMask = [UIView.AutoresizingMask.flexibleHeight]
}
override func layoutSubviews() {
self.layoutIfNeeded()
}
i get cell width fix without i am set that width. how may this issue solve?
here screenshots.
You need to make sure that your Estimate Size
is set to None
for your CollectionView.
Please do the following steps
Hopefully it will fix the problem
You can use collectionView delegate
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width:, height:)
}
for this you need to extend UICollectionViewDelegateFlowLayout
You have to use UICollectionViewDelegateFlowLayout
and implement sizeForItemAt
like following.
// MARK: - UICollectionViewDelegateFlowLayout -
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let sectionInset = (collectionViewLayout as! UICollectionViewFlowLayout).sectionInset
// Here you can set dynamic height for the individual cell according to your content size.
let referenceHeight: CGFloat = 100 // Approximate height of your cell
let referenceWidth = collectionView.safeAreaLayoutGuide.layoutFrame.width
- sectionInset.left
- sectionInset.right
- collectionView.contentInset.left
- collectionView.contentInset.right
return CGSize(width: referenceWidth, height: referenceHeight)
}
Here is an articale about it, you can follow this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With