UITableView with controller separate from ViewController

前端 未结 5 1792
感情败类
感情败类 2020-12-22 03:06

I\'m a newbie to Swift and XCode, taking a class in iOS development this summer. A lot of projects we\'re doing and examples I\'m seeing for UI elements like PickerViews, Ta

5条回答
  •  一向
    一向 (楼主)
    2020-12-22 03:29

    You can also use adapter to resolve this with super clean code and easy to understand, Like

    protocol MyTableViewAdapterDelegate: class {
        func myTableAdapter(_ adapter:MyTableViewAdapter, didSelect item: Any)
    }
    
    class MyTableViewAdapter: NSObject {
        private let tableView:UITableView
        private weak var delegate:MyTableViewAdapterDelegate!
    
        var items:[Any] = []
    
        init(_ tableView:UITableView, _ delegate:MyTableViewAdapterDelegate) {
            self.tableView = tableView
            self.delegate = delegate
            super.init()
            tableView.dataSource = self
            tableView.delegate = self
            tableView.rowHeight = UITableViewAutomaticDimension
            tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        }
    
        func setData(data:[Any]) {
            self.items = data
            reloadData()
        }
    
        func reloadData() {
            tableView.reloadData()
        }
    }
    
    extension MyTableViewAdapter: UITableViewDataSource, UITableViewDelegate {
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return items.count
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            cell.textLabel?.text = "Hi im \(indexPath.row)"
            return cell
        }
    
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            tableView.deselectRow(at: indexPath, animated: true)
            delegate?.myTableAdapter(self, didSelect: items[indexPath.row])
        }
    }
    

    Use Plug and Play

    class ViewController: UIViewController, MyTableViewAdapterDelegate {
    
        @IBOutlet var stateTableView: UITableView!
        var myTableViewAdapter:MyTableViewAdapter!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            myTableViewAdapter = MyTableViewAdapter(stateTableView, self)
        }
    
        func myTableAdapter(_ adapter: MyTableViewAdapter, didSelect item: Any) {
            print(item)
        }
    }
    

提交回复
热议问题