很多情況下,都會(huì)用到tableViewCell嵌套一個(gè)CollectionView,方便數(shù)據(jù)的展示與靈活控制,下面上代碼來實(shí)現(xiàn)它。
新建一個(gè)TableViewCell并勾選創(chuàng)建xib。然后在xib中拖一個(gè)CollectionView并設(shè)置好約束。然后創(chuàng)建一個(gè)CollectionViewCell并勾選創(chuàng)建xib,并處理好要展示的CollectionViewCell的布局。
TableViewCell中代碼:
import UIKit
class TableViewCell: UITableViewCell {
static let identifier = "TableViewCell"
//CollectionView數(shù)據(jù)源
public var bankArray: [Model] = []
// CollectionViewCell點(diǎn)擊
var gotoViewControllerCardClosure: ((_ bankId: Int)->Void)?
@IBOutlet weak var collectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
let flowLayout = UICollectionViewFlowLayout()
flowLayout.itemSize = CGSize(width: (PCScreenWidth - 30) / 3, height: (PCScreenWidth - 30) / 3)
flowLayout.minimumInteritemSpacing = 0;
flowLayout.minimumLineSpacing = 0;
collectionView.collectionViewLayout = flowLayout
collectionView!.register(UINib(nibName:"CollectionViewCell", bundle:nil),
forCellWithReuseIdentifier: "cell")
collectionView.delegate = self
collectionView.dataSource = self
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
extension TableViewCell: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return bankArray.count > 6 ? 6 : bankArray.count //最多顯示6個(gè)CollectionViewCell,根據(jù)需要自己調(diào)整
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell",
for: indexPath) as! CreditCardCollectionViewCell
let model = bankArray[indexPath.row]
//設(shè)置CollectionViewCell ...
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
gotoViewControllerCardClosure?(bankArray[indexPath.row].id)
}
}
ViewController中設(shè)置TableView的cell
let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier) as! TableViewCell
cell.bankArray = bankArray
cell. gotoViewControllerClosure = { [weak self] bankId in
guard let strongSelf = self else {
return
}
//跳轉(zhuǎn)需要處理的業(yè)務(wù)
//.......
}
return cell
OK,大功告成~ 基本思路就是這樣。如果展示效果不是自己想要的,再調(diào)整下對(duì)應(yīng)設(shè)置與代碼控制。