ios - tableView如何新建一个类作为数据源和代理?
PHPz
PHPz 2017-04-18 09:05:45
0
2
365

网上的 iOS 案例教程中,UITable 都是用 ViewController 作为数据源和代理,比如:

self.listTableView.dataSource = self;
self.listTableView.delegate   = self;

但是这样做 ViewController 会变得很长,如何新建一个文件来存储数据源和代理方法?

PHPz
PHPz

学习是最好的投资!

reply all(2)
Peter_Zhu

This is actually a question of how to split a very large source code.
Here are several methods recommended to you, all of which are better.

1. Independent datasource, delegate management class

@interface MyTableManager : NSObject <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

- (void)setupWithTableView:(UITableView *)tableView

@end


@interface MyTableManager ()

@property (nonatomic, strong) NSMutableArray *array;

@end 

@implement MyTableManager

- (void)setupWithTableView:(UITableView *)tableView
{
    if (_tableView != tableView) {
        _tableView = tableView;
        
        _tableView.delegate = self;
        _tableView.dataSource = self;
        // ...
        // _array = ?
    }
}

#param mark - DataSource
// ...
#param mark - Delegate
// ...
@end

Then you just need to initialize the manager at the appropriate place in the viewController, and then load the tableView.
The advantage of this method is that if you use the same management logic in many places, the code can be split very well.

If you just want to reduce the number of rows of viewController, and this management class is not suitable for each viewController, then there is another method, which is also good.


2. Use category to split files

// MyViewController.h
@interface MyViewController (TableView) <UITableViewDelegate, UITableViewDataSource>

@end

// MyViewController+TableView.m
@implement MyViewController (TableView)

// ...

@end

There is no one-size-fits-all solution, just find one that suits you.

巴扎黑

Both = your new class, just implement the protocol method in the new class

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template