有时要实现一个复杂的页面布局,单单使用 UITableView 实现不了,需要通过 UITableView 和 UICollectionView 结合实现,即每个单元格 tableViewCell 中都嵌套一个 collectionView。下面通过样例演示如何实现。
1,效果图
(1)表格中每一个单元格对应一个月份的图书列表。 (2)单元格中头部显示月份标题。内部通过 collectionView 显示当月所有书籍封面图片,数量不定。整个单元格高度自适应。 (3)这个样例其实只用多 section 的 collectionView 也能实现( 点击查看)。本文使用 UITableView + UICollectionView 演示如何实现同样的功能,
2,如何实现单元格高度自适应
(1)我们要对 collectionView 设置个高度约束。当在单元格中更新 collectionView 的数据时,要获取这个 collectionView 的真实的内容高度( contentSize.height),然后用 contentSize.height 来更新 collectionView 的高度约束。这样就实现了单元格内部 collectionView 的高度自适应。 (2)而对于单元格 tableViewCell 的高度自适应,是通过 AutoLayout 特性实现的。利用内容将 cell 撑起来。
1 2 3 4 | |
3,实现步骤
(1)新建一个自定义的 collectionView 单元格类: MyCollectionViewCell,同时勾选“ Also create XIB file”
(2)在 MyCollectionViewCell.xib 中添加一个 ImageView,并设置好约束。同时在对应的类中作关联
(3) MyCollectionViewCell.swift 代码如下:
1 2 3 4 5 6 7 8 9 10 11 | |
(4)新建一个自定义的 tableView 单元格类: MyTableViewCell ,同时勾选“ Also create XIB file ”
(5)在 MyTableViewCell.xib 中添加一个 Label 和一个 CollectionView,并设置好约束。同时在对应的类中作关联。 其中 Label 设置的是上、下、左、右4个约束:
CollectionView 设置的是左、右、下以及高度这个4个约束:
(6) MyTableViewCell.swift 代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | |
(7)在 StoryBoard 主视图中添加一个 TableView,并设置好约束。同时在对应的类中作关联。
(8) ViewController.swift 代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | |
源码下载:
hangge_1591.zip
功能修改:每个单元格只显示一行封面图片
上面的样例中,每个单元格内的图片是全部显示出来,有多少显示多少,高度自适应。 我们还可以换种展示方法,每个单元格,即每个 collectionView 只显示一行数据,图片如果多的话可以通过左右滑动查看。
1,效果图
2,实现原理
我们只需要把 collectionView 的滚动方向改成水平方向即可。
如果不需要显示横向的滚动条,可以去掉“ Shows Horizontal Indicator”的勾选。
原文出自: www.hangge.com 转载请保留原文链接: http://www.hangge.com/blog/cache/detail_1591.html