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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容