Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Width Cell in UICollectionView

enter image description here

I try to implement labels with UICollectionView. But I have to set the widths with dynamic labels length. I try to remove gaps in picture. I share some code. I use Nibs.

Thanks in advance.

layoutFCV.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
let filterCV = UICollectionView(frame: self.view.bounds, collectionViewLayout: layoutFCV)

--

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {       
    if collectionView == filterCollectionView {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FilterSelectionCollectionViewCell", for: indexPath) as! FilterSelectionCollectionViewCell
        return CGSize(width: cell.title.frame.width , height: self.filterCollectionView.frame.height)
    }  else {
        return CGSize(width: 10, height: 10)
    }
}
like image 873
Ali Ihsan URAL Avatar asked Dec 03 '18 08:12

Ali Ihsan URAL


2 Answers

Use this code:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let text = "Title"
    let width = self.estimatedFrame(text: text, font: UIFont.systemFont(ofSize: 14)).width
    return CGSize(width: width, height: 50.0)
}

func estimatedFrame(text: String, font: UIFont) -> CGRect {
    let size = CGSize(width: 200, height: 1000) // temporary size
    let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
    return NSString(string: text).boundingRect(with: size,
                                               options: options,
                                               attributes: [NSFontAttributeName: font],
                                               context: nil)
}
like image 190
nitin.agam Avatar answered Oct 08 '22 21:10

nitin.agam


extension ViewController: UICollectionViewDelegateFlowLayout {
     func collectionView(_ collectionView: UICollectionView, layout      collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
     return "String".size(withAttributes: [
       NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 14)
  ])
  }
 }
like image 29
Pramod Shukla Avatar answered Oct 08 '22 23:10

Pramod Shukla