IOS封装自定义Cell方法 IOS封装自定义Cell方法

IOS封装自定义Cell方法

很多时候Objective-C自带的cell样式根本无法满足我们的开发需求,身边又会有产品美工时不时盯着,一点偏差都不能有,于是不得不自己去创建cell。自定义cell的最简便方式就是在tableview的cellforrow方法里去布局cell的样式,但这样就不可避免的会造成Controller代码量超多,非常臃肿,因此实际开发中我们应当多应用封装的思想。

首先我们先自定义个Cell:

[objc]  view plain  copy
  1. @interface Mycell : UITableViewCell  
  2.   
  3. +(instancetype)cellWithtableView:(UITableView *)tableview;  
  4.   
  5. @property(nonatomic,strong)DateModel *model;  
  6.   
  7. @property(nonatomic,weak) id<MycellDelegate> delegate;  
  8.   
  9. @end  

上述代码中的代理是cell中自定义按钮的点击事件,详情可见上一篇博文。

在.m文件中实现类方法:

[objc]  view plain  copy
  1. +(instancetype)cellWithtableView:(UITableView *)tableview  
  2. {  
  3.     static NSString *ID = @"cell";  
  4.     Mycell *cell = [tableview dequeueReusableCellWithIdentifier:ID];  
  5.     if(!cell)  
  6.     {  
  7.         cell = [[Mycell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];  
  8.         cell.selectionStyle = UITableViewCellSelectionStyleNone;  
  9.         cell.textLabel.font = [UIFont systemFontOfSize:13.0];  
  10.     }  
  11.     return cell;  
  12.       
  13. }  
  14.   
  15.   
  16. //重写布局  
  17. -(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier  
  18. {  
  19.     self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];  
  20.     if(self)  
  21.     {  
  22.         self.button = [[UIButton alloc] initWithFrame:CGRectMake(00, [UIScreen mainScreen].bounds.size.widthself.frame.size.height)];  
  23.         [self.button setTitle:@"我是按钮点我" forState:UIControlStateNormal];  
  24.         [self.button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];  
  25.         self.button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;  
  26.         self.button.titleLabel.font = [UIFont systemFontOfSize:12.0];  
  27.         [self.contentView addSubview:self.button];  
  28.         [self.button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];  
  29.     }  
  30.     return self;  
  31. }  

通过一系列方法封装后,我们在viewcontroller中只需要少量代码即可完成自定义cell的创建。

[objc]  view plain  copy
  1. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
  2. {  
  3.     Mycell *cell = [Mycell cellWithtableView:tableView];  
  4.     cell.model = self.Array[indexPath.row];  
  5.     cell.delegate = self;  
  6.     return cell;  
  7. }  

如此一来不仅完美的完成了cell的自定义创建,代码看起来也很美观,在同事review代码的时候就可以避免被吐槽的尴尬==。当然了,还会有另一种情况就是不同行数的cell长得不一样,我的做法是在类方法中加个参数,indexPath,传入这个参数,可以让类方法根据不同的行数创建不同的cell。

猜你喜欢

转载自blog.csdn.net/mr_tangit/article/details/80619897