ios - UITableViewCell 中的 UICollectionView?

标签 ios swift uitableview uicollectionview

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

我已经整理好了标签和边框什么的,但是考虑到内容是动态的,我不知道用什么来组织里面。

我已经阅读了有关 FlowLayout 的内容,但我不确定如何使用它,还有关于 UICollectionView 的内容,但是 Collection View 所能提供的只是单元格内的水平滚动,这是一个不适合的功能我的需求。

你能给我一些关于如何实现这一目标的建议吗?

最佳答案

这是 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 方法中清理格式。

希望这对您有所帮助!

关于ios - UITableViewCell 中的 UICollectionView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37558019/

相关文章:

ios - Facebook SDK 3.1 for iOS,通过应用程序切换登录时永远不会调用完成处理程序

ios - 委托(delegate)给另一个 View Controller 不起作用

ios - 影子滞后于用户界面

ios - 带有水平包装单元格的 UITableView

iphone - 在 Storyboard 中创建自定义 UITableViewCell

ios - uitableview 单元格的背景

ios - 从应用程序内部订阅日历

ios - 应用内购买错误

ios - 从 NSObject 派生时,Swift iOS 内存泄漏指示 XCode8

objective-c - 如何手动调用 UITableView