Separating Data Source to another class in Swift

前端 未结 3 697
时光取名叫无心
时光取名叫无心 2020-12-13 20:21

I\'m trying to keep my view controllers clean as described in this article objc.io Issue #1 Lighter View Controllers. I tested this method in Objective-C and it works fine.

3条回答
  •  情书的邮戳
    2020-12-13 20:42

    I used the below code, for more generic approach, as a try..

    import UIKit
    
    class CustomDataSource: NSObject, UITableViewDataSource {
    
        typealias ConfigureCellClosure = (_ item: ItemsType, _ cell: CellType) -> Void
        private var items: [ItemsType]
        private let identifier: String
        private var configureCellClosure: ConfigureCellClosure
    
    
        init(withData items: [ItemsType], andId identifier: String, withConfigBlock config:@escaping ConfigureCellClosure) {
    
            self.identifier = identifier
            self.items      = items
            self.configureCellClosure = config
        }
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return items.count
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: self.identifier, for: indexPath) as! CellType
            configureCellClosure(items[indexPath.row], cell)
            return cell
        }
    
        func item(at indexpath: IndexPath) -> ItemsType {
    
            return items[indexpath.row]
        }
    
    }
    

    In view controller

       var dataSource: CustomDataSource?
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
             dataSource = CustomDataSource(withData: customDataStore.customData(), andId: CustomTableViewCell.defaultReuseIdentifier) { (cellObject, cell) in
                cell.configureCell(with: cellObject)
            }
            customTableView.dataSource = dataSource
    
            // Do any additional setup after loading the view.
    }
    

    Used this approach in my small project WorldCountriesSwift

提交回复
热议问题