Swift泛型高阶使用-自定义dataSource 几行代码完成
2020-11-26 本文已影响0人
J扣歪
tableView代码展示
tableView = UITableView()
self.view = tableView
dataSource = TableViewNormalDataSource.init(configureCell: { (table, model, indexPath) -> UITableViewCell in
var cell = table.dequeueReusableCell(withIdentifier: "cell_id")
if cell == nil {
cell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "cell_id")
}
cell?.textLabel?.text = (model?.title ?? "") + "\(indexPath.row)"
cell?.detailTextLabel?.text = (model?.subTitle ?? "") + "\(indexPath.row)"
return cell!
})
dataSource?.configureRowHeight({ (table, model, indexPath) -> CGFloat in
100
})
tableView?.dataSource = dataSource
tableView?.delegate = dataSource
self.loadData()
collectionView代码展示
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 1
layout.minimumInteritemSpacing = 1
collectionView = UICollectionView.init(frame: .zero,collectionViewLayout: layout)
collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell_id")
collectionView?.backgroundColor = .white
self.view = collectionView
dataSource = CollectionViewNormalDataSource.init(configureItem: { (collection, model, indexPath) -> UICollectionViewCell in
let cell = collection.dequeueReusableCell(withReuseIdentifier: "cell_id", for: indexPath)
cell.backgroundColor = model
return cell
})
dataSource?.configureItemSize({ (collection, collectionViewLayout, model, indexPath) -> CGSize in
CGSize(width: (UIScreen.main.bounds.size.width/3) - 2, height: UIScreen.main.bounds.size.width/3)
})
dataSource?.didSelectItem({[weak self] (collection, model, indexPath) in
let alert = UIAlertController.init(title: nil, message: "你点击了第\(indexPath.row+1)个", preferredStyle: .alert)
let action = UIAlertAction.init(title: "确定", style: .cancel, handler: nil)
alert.addAction(action)
self?.present(alert, animated: true, completion: nil)
})
collectionView?.delegate = dataSource
collectionView?.dataSource = dataSource
dataSource?.addData(colors)
demo 地址