自定义tableViewCell

自定义tableViewCell
 
1、独立使用xib创建的cell不需要使用:注册cell,不然会使用不了,如下代码
[self.tableView registerClass:[ableViewCell class] forCellReuseIdentifier:@“actionCell"];
问:那如何加载呢:(使用NSBundle)
最好的方法是在这个cell的类中定义一个方法,如下:
+(instancetype)actionCellWithTableView:(UITableView *)tableView{
    IMUActionsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:actionCell];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"IMUActionsTableViewCell" owner:nil options:nil] firstObject];
        NSLog(@"创建了一个cell");
    }
    return cell;
}
 
2、在哪需要使用注册cell
答:当在tableView中自定义cell时,用类绑定cell时,才需要注册cell。别忘记了,自定义的tableViewcontroller+xib,是不能在tableView中自定义cell的,只有在storyBoard中才行。
 
//-----------------------------------------------------
步骤:
1、创建一个tableViewCell的类+xib
2、设计好cell的内容,如下图:
3、编写代码
//1、头文件
#import “GDataModel.h"
@interface GActionsTableViewCell : UITableViewCell
//cell的数据
@property(nonatomic,strong) GDataModel *data;
//类方法创建cell实例
+(instancetype)allActionCellWithTableView:(UITableView *)tableView;
 
@end
 
//2、.m文件
#import "GActionsTableViewCell.h"
#import <SDWebImage/UIImageView+WebCache.h>
#define GCell @“GCell"
@interface GActionsTableViewCell()
//文本
@property (weak, nonatomic) IBOutlet UILabel *TitleLabel;
//按钮
@property (weak, nonatomic) IBOutlet UIButton *JionBtn;
//图片
@property (weak, nonatomic) IBOutlet UIImageView *Image;
@end
 
@implementation GActionsTableViewCell
 
- (void)awakeFromNib {
//    self.actionTitleLabel.text = self.actionData.actionTitle;
   
}
//setter方法时,完成对控件的赋值
-(void)setdata:(IMUActionDataModel *)data{
    _data = data;
    self.TitleLabel.text = _data.Name;
    NSString *statusStr = nil;
    if (_data.registration) {
        statusStr = @"已报名";
        self.JionBtn.enabled = NO;
        self.JionBtn.backgroundColor = [UIColor lightGrayColor];
    }else{
        statusStr = @"报名";
    }
    [self.JionBtn setTitle:statusStr forState:UIControlStateNormal];
    [self.Image sd_setImageWithURL:[NSURL URLWithString:_data.ImageUrl] placeholderImage:nil];
}
//根据tableView创建cell实例
+(instancetype)allActionCellWithTableView:(UITableView *)tableView{
    GActionsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:GCell];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"GActionsTableViewCell" owner:nil options:nil] firstObject];
        NSLog(@"创建了一个cell");
    }
    cell.JionBtn.layer.cornerRadius = 3;
    return cell;
}
//实现按钮事件
- (IBAction)jionUsBtnClicked:(UIButton *)sender {
    UIButton *bt = sender;
    NSString *str = bt.titleLabel.text;
    NSLog(@"str : %@",str);
}
@end
 
4、使用
GActionsTableViewCell *cell = [IMUAllActionsTableViewCell allActionCellWithTableView:tableView];
GDataModel *data = self.Arrays[indexPath.row];
cell.actionData = data;
return cell;
原文地址:https://www.cnblogs.com/lignpeng/p/5444623.html