UITableView嵌套UICollectionView

demo

UITableView嵌套UICollectionView其实就是在Cell当中添加UICollectionView,并设置其代理和数据源。所以关键代码在UITableViewCell当中。

  • 在UITableViewCell中设置UICollectionView
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)

let layout = UICollectionViewFlowLayout.init()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.sectionInset = UIEdgeInsets.init(top: 5, left: 5, bottom: 5, right: 5)
layout.itemSize = CGSize(width: (kScreenWidth - 25) / 4, height: (kScreenWidth - 25) / 4)

collectionView = UICollectionView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: (kScreenWidth - 25) / 4 * 3), collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.register(NestingCollectionViewCell.self, forCellWithReuseIdentifier: "Nesting")
collectionView.delegate = self
collectionView.dataSource = self;
self.contentView.addSubview(collectionView)
}
  • 设置代理和数据源
1
2
3
4
5
6
7
8
9
10
11
12
13
14

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.collectionDataArr.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Nesting", for: indexPath)

cell.backgroundColor = UIColor.yellow

return cell

}
  • 重点是点击代理的触发,因为是在Cell中实现的代理在Controll中无法直接获取到didSelectItemAt的值因此需要自定义一个代理

1.声明一个delegate

1
weak var delegate : SelectCollectionItemDelegate?

2.设置delegate方法

1
2
3
@objc protocol SelectCollectionItemDelegate {
@objc optional func selectCollectionItem(indexPath : IndexPath)
}

3.实现代理方法 在UICollectionViewDelegate的didSelectItemAt方法中实现

1
2
3
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.delegate!.selectCollectionItem!(indexPath: indexPath)
}

4.接收自定义代理 在要实现的Controller中添加自定义代理并设置代理 此处为SelectCollectionItemDelegate 最后实现代理

  • collectioncell.delegate = self 此处很关键
1
2
3
func selectCollectionItem(indexPath: IndexPath) {
print(indexPath)
}

自此一个简单的UITableView嵌套UICollectionView就算完成Demo

  • 如有误不吝赐教!!!!!