UITableViewCell中的UICollectionView?

时间:2016-06-01 01:22:38

标签: ios swift uitableview uicollectionview

我必须构建一个自定义的UITableViewCell,但我不确定如何处理内容。指定的设计如下所示:

我已经整理了标签和边框以及所有内容,但考虑到内容是动态的,我不知道如何使用它来组织内部。

我已经阅读过关于FlowLayout的内容,但我不确定如何使用它,也不知道UICollectionView,但集合视图可以提供的所有内容都是单元格内的水平滚动,这个功能没有&# 39;不符合我的需要。

您能否就如何实现这一目标给我一些建议?

1 个答案:

答案 0 :(得分:2)

这是使用动态单元大小调整的UICollectionView的一个非常基本的实现。

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

您必须根据需要在sizeForItemAtIndexPath方法中清理格式。

希望这有帮助!