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。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值