为从 UIViewController 中删除 UITableViewDataSource 和 UICollectionViewDataSource 代码,提供一个简单的 Objective-C 和 Swift 实现,并在 UIViewControllers 之间共享。
'ABDataSourceController', '~> 1.1'
添加到 Podfile),或克隆此仓库并将 ABDataSourceController/objc
文件夹的内容拖放到项目中。ABTableViewDataSourceController
协议的自定义数据源控制器对象。#import "ABDataSourceController.h"
@interface CustomDataSourceController : NSObject <ABTableViewDataSourceController>
@property (nonatomic, assign) IBOutlet UITableView *tableView;
@property (nonatomic, assign) IBOutlet UIViewController *viewController;
@end
@implementation CustomDataSourceController {
NSArray *_dataSource;
}
@synthesize tableView = _tableView;
@synthesize viewController = _viewController;
@end
refreshDataSourceWithCompletionHandler
方法来加载数据源- (void)refreshDataSourceWithCompletionHandler:(void (^)())completion {
[self loadDataSource];
if (completion)
completion();
}
UITableViewDataSource
和 UITableViewDelegate
代码#pragma mark UITableViewDataSource Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _dataSource.count;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"DefaultCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
cell.textLabel.text = [_dataSource objectAtIndex:indexPath.row];
return cell;
}
tableView
和 viewController
端口连接,并将表视图的 dataSourceController
端口连接到您的自定义对象。您就绪了!dataSourceController
属性,您就绪了!#import "UITableView+DataSourceController.h"
@implementation MainViewController {
IBOutlet UITableView *tableView;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
// setup data source controller
CustomDataSourceController *dataSourceCtrl = [[CustomDataSourceController alloc] init];
dataSourceCtrl.tableView = tableView;
dataSourceCtrl.viewController = self;
tableView.dataSourceController = dataSourceCtrl;
// load data source
[tableView.dataSourceController refreshDataSourceWithCompletionHandler:nil];
}
@end
ABCollectionViewDataSourceController
协议。ABDataSourceController 是由 Alex Bumbu 创建的。
ABDataSourceController 可在 MIT 许可证下使用。有关更多信息,请参阅 LICENSE 文件。如果您不想注明出处,请联系 Alex Bumbu。