alexclp
alexclp

Reputation: 201

UICollectionView in UITableViewCell?

I have to build a custom UITableViewCell, but I'm not sure about how to handle the content. The specified design would look like this:

I have sorted out the labels and the borders and everything, but considering the fact that the content is dynamic, I don't know what to use to organize it inside.

I have read about the FlowLayout, but I'm not sure how to use it, and also about the UICollectionView, but all that the collection view can provide is an horizontal scroll inside the cell, a feature that doesn't fit my needs.

Can you give me some suggestions about how to achieve this?

Upvotes: 0

Views: 326

Answers (1)

DJohnson
DJohnson

Reputation: 919

Here is a very basic implementation of UICollectionView, using dynamic cell sizing.

class CollectionViewController: UICollectionViewController {

  @IBOutlet var myCollectionView: UICollectionView!

  let tags = [
    "Web Design",
    "ADWE",
    "Busisness functions",
    "Comics",
    "Web",
    "News in the Middle East",
    "Albanian",
    "Possession of machetes",
    "Nuclear physics",
    "Cookery",
    "Cross stitiching"
  ]

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

  override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return tags.count

  }

  override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("dynamicCell", forIndexPath: indexPath)
    cell.layer.borderColor = UIColor.grayColor().CGColor
    cell.layer.borderWidth = 1.0
    cell.layer.cornerRadius = cell.frame.height / 2.0
    let tagLabel = cell.viewWithTag(100) as? UILabel
    tagLabel?.text = tags[indexPath.row]
    return cell
  }

}

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

    let tagLabel = UILabel()
    tagLabel.text = tags[indexPath.row]
    let size = tagLabel.intrinsicContentSize()
    let cellSize = CGSizeMake(size.width + 40, size.height + 20)  //added 40 to width to add space around label.

    return cellSize

  }
}

enter image description here

You would have to clean up the formatting as needed in the sizeForItemAtIndexPath method.

Hope this helps!

Upvotes: 2

Related Questions