IOS封装自定义Cell方法
很多时候Objective-C自带的cell样式根本无法满足我们的开发需求,身边又会有产品美工时不时盯着,一点偏差都不能有,于是不得不自己去创建cell。自定义cell的最简便方式就是在tableview的cellforrow方法里去布局cell的样式,但这样就不可避免的会造成Controller代码量超多,非常臃肿,因此实际开发中我们应当多应用封装的思想。
首先我们先自定义个Cell:
- @interface Mycell : UITableViewCell
- +(instancetype)cellWithtableView:(UITableView *)tableview;
- @property(nonatomic,strong)DateModel *model;
- @property(nonatomic,weak) id<MycellDelegate> delegate;
- @end
上述代码中的代理是cell中自定义按钮的点击事件,详情可见上一篇博文。
在.m文件中实现类方法:
- +(instancetype)cellWithtableView:(UITableView *)tableview
- {
- static NSString *ID = @"cell";
- Mycell *cell = [tableview dequeueReusableCellWithIdentifier:ID];
- if(!cell)
- {
- cell = [[Mycell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
- cell.selectionStyle = UITableViewCellSelectionStyleNone;
- cell.textLabel.font = [UIFont systemFontOfSize:13.0];
- }
- return cell;
- }
- //重写布局
- -(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
- {
- self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
- if(self)
- {
- self.button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, self.frame.size.height)];
- [self.button setTitle:@"我是按钮点我" forState:UIControlStateNormal];
- [self.button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
- self.button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
- self.button.titleLabel.font = [UIFont systemFontOfSize:12.0];
- [self.contentView addSubview:self.button];
- [self.button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
- }
- return self;
- }
通过一系列方法封装后,我们在viewcontroller中只需要少量代码即可完成自定义cell的创建。
- -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- {
- Mycell *cell = [Mycell cellWithtableView:tableView];
- cell.model = self.Array[indexPath.row];
- cell.delegate = self;
- return cell;
- }
如此一来不仅完美的完成了cell的自定义创建,代码看起来也很美观,在同事review代码的时候就可以避免被吐槽的尴尬==。当然了,还会有另一种情况就是不同行数的cell长得不一样,我的做法是在类方法中加个参数,indexPath,传入这个参数,可以让类方法根据不同的行数创建不同的cell。