美文网首页
swift 协议泛型TableView viewModel 模板

swift 协议泛型TableView viewModel 模板

作者: 秋叶红90 | 来源:发表于2021-01-28 11:32 被阅读0次

    协议声明与实现

    protocol SHViewModelProtocol:UITableViewDataSource,UITableViewDelegate {
        associatedtype ItemType
        var dataArray:[ItemType] {set get}
    }
    protocol SHCellProtocol {
        associatedtype ItemType
        var model:ItemType? {set get}
        mutating func updateData(dataArray:[ItemType],index:IndexPath);
    }
    extension SHCellProtocol{
        mutating func updateData(dataArray:[ItemType],index:IndexPath) {
            print("执行了====")
            if dataArray.count > index.row {
                self.model = dataArray[index.row]
            }
        }
    }
    
    class SHBaseTableCell<Element>: UITableViewCell,SHCellProtocol {
        
        
        typealias ItemType = Element
        var model:Element?
    
    }
    
    class SHBaseTableViewModel<Element>: NSObject,SHViewModelProtocol {
        var dataArray: [Element] = [Element]()
        var listView:UITableView?
        typealias ItemType = Element
        var registNibCells:[SHBaseTableCell<Element>.Type] = [SHBaseTableCell<Element>.Type]()
        func bindViewModel(listView:UITableView,registNibCells:[SHBaseTableCell<Element>.Type]) {
            self.listView = listView
            self.registNibCells = registNibCells
            for item in registNibCells {
                let nib = UINib.init(nibName: "\(item.self)", bundle: nil)
                listView.register(nib, forCellReuseIdentifier: "\(item.self)")
            }
            
            listView.dataSource = self
            listView.delegate = self
            
        }
        
        func updateData(list:[Element]) {
            self.dataArray = list
            
            self.listView?.reloadData()
        }
        
        
        
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            
            return self.dataArray.count
        }
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
             
            let cellType = self.registNibCells.first!
            let cell = tableView.dequeueReusableCell(withIdentifier: "\(cellType)", for: indexPath)
            if var item = cell as? SHBaseTableCell<Element> {
                item.updateData(dataArray: self.dataArray, index: indexPath)
                
            }
            
            return cell
        }
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            
            
            
        }
    }
    
    
    
    ``

    相关文章

      网友评论

          本文标题:swift 协议泛型TableView viewModel 模板

          本文链接:https://www.haomeiwen.com/subject/tguttltx.html