0

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?

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Thinking more about this, if the order of the tags isn't important, than I would write a sorting function to optimize layout (and probably do full justification).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.