Simple way to separate UITableview datasource and delegate from main UIViewController class?

前端 未结 4 1084
终归单人心
终归单人心 2021-01-02 08:19

The typical UITableView usage pattern is to have the main UIViewController become a target datasource and delegate for the UITableView it is holding on to.

Are there

4条回答
  •  不知归路
    2021-01-02 08:54

    First thing is if you're using a UITableViewController subclass with interface builder you will want to disconnect the delegate and datasource outlets that are already hooked up by default. (Hint, look in the connections inspector). Check even if you have a tableView inside a viewController.

    Second create your classes and make sure they conform to and . You're probably going to have to declare this contract in the .h file if you're using objc.

    Third, In your view controller instantiate this class or two separate classes somewhere like viewDidLoad, and then assign self.tableView.delegate = myCustomDelegateInstance and self.tableView.dataSource = myCustomDataSourceInstance.

    Now, any calls that come through the controller will be dispatched to your custom handlers. Pretty basic.

    The only reason to really do this is if you 1) have a very bloated controller, or 2) you need to reuse the dataSource and delegate methods somewhere else and you want to avoid code repetition. Otherwise, it's probably better practice to leave it put.

提交回复
热议问题