将collectionviewcell大小设置为等于内容

时间:2015-08-30 12:34:23

标签: ios swift uicollectionview

我创建了一个collectionViewCell,它包含一个imageView和一个标签。但是,标签设置为sizeToFit,因此它将根据内容调整大小。问题是我似乎无法将collectionVieCell大小设置为单元格内容的大小。这是我的代码:

enter image description here

自定义单元格

class BrowseCell: UICollectionViewCell {

    @IBOutlet var mainImageView:UIImageView?
    @IBOutlet var titleLabel:UILabel?


    override init(frame: CGRect) {
        super.init(frame: CGRect())



        self.backgroundColor = UIColor.whiteColor()

        titleLabel?.numberOfLines = 0
        titleLabel?.sizeToFit()


        self.contentView.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth







    }
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

collectionView委托方法

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ItemCell", forIndexPath: indexPath) as! BrowseCell






        cell.titleLabel?.text = testText




        return cell
    }

    // MARK: WaterfallLayoutDelegate

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




        return CGSizeMake(140, 150)
    }

    func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
        var reusableView: UICollectionReusableView? = nil



        return reusableView!
    }

1 个答案:

答案 0 :(得分:0)

我不认为您可以在加载后修改单元格大小,您可以尝试使用下面使用的方法。

您可以尝试将索引路径放在&获得标签宽度。

您还可以将要加载的所有文本放入数组&根据字符数设置宽度。

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

 let flickrPhoto =  photoForIndexPath(indexPath)
      //2
      if var size = flickrPhoto.thumbnail?.size {
        size.width += 10
        size.height += 10
        return size
       }
      return CGSize(width: 100, height: 100)
  }
相关问题