0

The problem is that I have a different UILabel content for each cell and I want the width of the cell fixed and the hight flexible depending on the content which is UILabel hight , I tried deferent solutions for this problem and watched several tutorials but unfortunately it did not workout for me .

**I have one view controller and two collection views and I just need one of them to have a flexible hight **

extension TextViewController : UICollectionViewDelegateFlowLayout {

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

    if collectionView == PagesCollectionView
    {
    return CGSizeMake(44.0, 44.0)
    }
    else {

        width = UIScreen.mainScreen().bounds.width - CGFloat( 14 )

        return CGSizeMake( width , hight )
    }


}

Edit 1 :

Is there a simple way to do this like in table view ?

example : -

override func viewDidLoad() {

super.viewDidLoad()

self.tableView.estimatedRowHeight = 80
self.tableView.rowHeight = UITableViewAutomaticDimension }
  • check this link might help you http://stackoverflow.com/questions/27285258/collectionview-dynamic-cell-height-swift – Subin K Kuriakose Jul 08 '16 at 04:33
  • Thx , it is a good approach but not what I need , I want the hight to be equal to The Label hight . is it possible to access the cell.label.hight from this fun ? I tried to access it but didn't figure out how to do it . – user6510240 Jul 08 '16 at 11:11

1 Answers1

0

I will assume that you are going to display a text inside the cell

extension TextViewController : UICollectionViewDelegateFlowLayout {

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

        if collectionView == PagesCollectionView
        {
        return CGSizeMake(44.0, 44.0)
        }
        else {

            let width = UIScreen.mainScreen().bounds.width - CGFloat( 14 )
            let text = YourDataSource[indexPath.item].text
            let size = CGSizeMake(width, 800) // just any arbitrary height to make it compile
            let options = NSStringDrawingOptions.UsesFontLeading.union(.UsesLineFragmentOrigin)
            let estimatedFrame = NSString(string: text).boundingRectWithSize(size, options: options, attributes: [NSFontAttributeName:UIFont.systemFontOfSize(16)], context: nil)
            return CGSizeMake(width , estimatedFrame.height)
        }


    }
Faisalocs
  • 1
  • 1