专栏名称: Cocoa开发者社区
CocoaChina苹果开发中文社区官方微信,提供教程资源、app推广营销、招聘、外包及培训信息、各类沙龙交流活动以及更多开发者服务。
目录
相关文章推荐
51好读  ›  专栏  ›  Cocoa开发者社区

iOS开发 精简TableView

Cocoa开发者社区  · 公众号  · ios  · 2017-06-05 11:47

正文

翻译、修改自objc.io

原文链接: Clean Table View Code



导语


TableView 是iOS app 中最常用的控件,许多代码直接或者间接的关联到table view任务中,包括提供数据、更新tableView、控制tableView行为等等。下面会提供保持tableView代码整洁和结构清晰的方法。


UITableViewController vs. UIViewController


TableViewController的特性


table view controllers可以读取table view的数据、设置tabvleView的编辑模式、反应键盘通知等等。同时Table view controller能够通过使用UIRefreshControl来支持“下拉刷新”。


Child View Controllers


tableViewController也可以作为child view controller添加到其他的viewController中,然后tableViewController会继续管理tableView,而parentViewController能管理其他我们关心的东西。


-(void)addDetailTableView

{

DetailViewController *detail = [DetailViewController new];

[detail setup];

detail.delegate = self;

[self addChildViewController:detail];

[detail setupView];

[self.view addSubview:detail.view];

[detail didMoveToParentViewController:self];

}


如果在使用以上代码时,需要建立child View controller 和 parent view controller之间的联系。比如,如果用户选择了一个tableView里的cell,parentViewController需要知道这件事以便能够响应点击时间。所以最好的方法是table view controller定义一个协议,同时parent view controller实现这个协议。


@protocol DetailViewControllerDelegate

-(void)didSelectCell;

@end


@interface ParentViewController ()

@end


@implementation ParentViewController

//....

-(void)didSelectCell

{

//do something...

}

@end


虽然这样会导致view controller之间的频繁交流,但是这样保证了代码的低耦合和复用性。


分散代码


在处理tableView的时候,会有各种各样不同的,跨越model层、controller层、view层的任务。所以很有必要把这些不同的代码分散开,防止viewController成为处理这些问题的“堆填区”。尽可能的独立这些代码,能够使代码的可读性更好,拥有更好的可维护性与测试性。


这部分的内容可以参考 《iOS开发 简化view controller》 ,而在tableView这一章中,将会专注于如何分离view和viewController


消除ModelObeject和Cell之间的隔阂


在很多情况下,我们需要提交我们想要在view层展示的数据,同时我们也行维持view层和model层的分离,所以tableView中的dateSource常常做了超额的工作:


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

Cell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];

[cell setup];

NSString *text = self.title;

cell.label.text = text;

UIImage *photo = [UIImage imageWithName:text];

cell.photoView.image = photo;

}


这样dataSorce会变得很杂乱,应该将这些东西分到cell的category中。


@implementation Cell (ConfigText)


-(void)configCellWithTitle:(NSString *)title

{

self.label.text = title;

UIImage *photo = [UIImage imageWithName:title];

cell.photoView.image = photo;

return cell;

}


这样的话dataSource将会变得十分简单。


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath







请到「今天看啥」查看全文