13.2.5 UICollectionViewCell

13.2.5 UICollectionViewCell

正如UITableViewCell的那样,UICollectionViewCell也可以被继承,做一些定制的Cell开发。首先创建一个Cocoa Touch Class,选择UICollectionViewCell作为基类,并生成XIB文件,如图13.2.10所示:

图13.2.10 创建自定义的UICollectionViewCell

点击“Next”,Xcode为我们生成了一个CustomCollectionViewCell.swift以及CustomCollection ViewCell.xib文件。点击xib文件,如图13.2.11所示:

图13.2.11 CustomCollectionViewCell.xib

为CustomCollectionViewCell增加两个Label,用于展示书名和简介,如图13.2.12所示:

图13.2.12 为CustomCollectionViewCell增加两个Label

通过Assistant editor将两个Label和CustomCollectionViewCell中的属性关联起来:

接着我们就可以使用CustomCollectionViewCell作为展示的Cell,代码如下:

动手写13.2.3 UICollectionViewPractise->ViewController.swift

几乎和UITableView的实现一致,不过需要注意:UICollectionView需要修改FlowLayout才能更改每个单元(Item)的大小,如图13.2.13所示:

图13.2.13 Collection View Flow Layout

修改了Item Size之后,再次运行模拟器,如图13.2.14所示:

图13.2.14 修改了Item Size的Collection View

模拟器展示了自定义的Cell,并且大小与初始时的相比产生了变化。如果还需为Cell填充数据,可以效仿UITableView中的BookModel再做一次。