Swift泛型高阶使用-自定义dataSource 几行代码完成tableView/collectionView配置

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 地址

https://github.com/jqygithud/SwiftDataSource.git

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容