当前应用都会比较复杂,一个tableView的列表会有多种cell,若是都放在控制器中处理,各类cell利用if,switch判断也会达到效果,可是控制器就会变得很臃肿。其实咱们能够利用协议来处理达到效果。而且控制中就不多的代码 1.咱们能够建立一个协议文件ModelConfigProtocol.hgit
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@protocol ModelConfigProtocol <NSObject>
@optional
///获取cell的复用标识
-(NSString *)cellReuseIdentifier;
///获取cell的高度
-(CGFloat)cellHeightWithindexPath:(NSIndexPath*)indexPath;
///点击事件
-(void)cellDidSelectRowAtIndexPath:(NSIndexPath*)indexPath other:(_Nullable id)other;
-(UITableViewCell*)tableView:(UITableView *)tableView reuseIdenyifier:(NSString *)reusedItentifier;
@end
复制代码
2.建立一个基类模型 BaseModel.h,而且遵照协议,实现协议方法github
#import "BaseModel.h"
@implementation BaseModel
- -(NSString *)cellReuseIdentifier {
return @"";
}
-(CGFloat)cellHeightWithindexPath:(NSIndexPath *)indexPath {
return 0.0;
}
-(void)cellDidSelectRowAtIndexPath:(NSIndexPath *)indexPath other:(id)other {
}
-(UITableViewCell*)tableView:(NSString *)tableView reuseIdenyifier:(NSString *)reusedItentifier {
UITableViewCell *cell = [[UITableViewCell alloc]init];
return cell;
}
@end
复制代码
3.建立一个基类Cell,其他cell继承基类Cell,而且设置遵照协议的模型为其属性 @property(nonatomic,strong)idmodel;swift
子类Cell重写model的set方法,基类的cell的model的set方法实现一下,不须要作处理,真正处理的是放在子类的cell里,根据具体事务具体分析。markdown
4.控制器中建立cell的时候就能够不用判断来写了oop
-(void)viewDidLoad {
[super viewDidLoad];
AModel *modelA = [[AModel alloc]init];
BModel *bmodel = [[BModel alloc]init];
CModel *cmodel = [[CModel alloc]init];
DModel *dmodel = [[DModel alloc]init];
self.dataArray = [NSMutableArray array];
[self.dataArray addObject:modelA];
[self.dataArray addObject:bmodel];
[self.dataArray addObject:cmodel];
[self.dataArray addObject:dmodel];
self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
self.tableView.dataSource = self;
self.tableView.delegate = self;
self.tableView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:self.tableView];
self.tableView.tableFooterView = [[UIView alloc]init];
[self.tableView reloadData];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
id <ModelConfigProtocol>model = self.dataArray[indexPath.row];
BaseCell *cell = (BaseCell *)[model tableView:tableView reuseIdenyifier:[model cellReuseIdentifier]];
cell.model = model;
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
id <ModelConfigProtocol>model = self.dataArray[indexPath.row];
return [model cellHeightWithindexPath:indexPath];
}
复制代码
oc,swift demo地址 github.com/suifumin/Mo…ui