·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> 自定义uitableviewcell

自定义uitableviewcell

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

新建继承自uitableviewcell的子类

xib自定义样式并指定其重用标示

配置cell数据

#import <UIKit/UIKit.h>

@interface CellStyleTwo : UITableViewCell
//工号
@PRoperty (weak, nonatomic) IBOutlet UILabel *userCode;
//电话
@property (weak, nonatomic) IBOutlet UILabel *phoneNumber;
/**
 *  配置 cell数据
 */
-(void)configureCellStyleTwo:(id)data;


@end
/**
 *  配置 cell数据
 *
 *  @param data
 */
-(void)configureCellStyleTwo:(id)data
{
    //如果数据是字典
    NSDictionary* dictionary=(NSDictionary*)data;
    if (dictionary)
    {
        self.userCode.text=dictionary[@"usercode"];
        self.phoneNumber.text=dictionary[@"userTel"];
    }
}

 对于是不是需要重写初始化,得看使用方法,如果是这样使用的话就不需要

                       [self.tableView registerNib:[UINib nibWithNibName:@"CellStyleTwo"
                                                                  bundle:[NSBundle mainBundle]]
                            forCellReuseIdentifier:@"CellStyleTwo"];

因为这种方式系统是直接查找得指定资源,不会使用默认创建方式

下面就需要

                       [self.tableView registerClass:[CellStyleTwo class]
                              forCellReuseIdentifier:@"CellStyleTwo"];
-(nonnull instancetype)initWithStyle:(UITableViewCellStyle)style
                     reuseIdentifier:(nullable NSString *)reuseIdentifier
{
    self=[super initWithStyle:style
              reuseIdentifier:reuseIdentifier];
    return [[[NSBundle mainBundle] loadNibNamed:@"CellStyleTwo"
                                         owner:self
                                       options:nil] firstObject];
}

这种方式仅仅是指定了注册的类,系统会使用默认的方式创建,但并不是我们所期望的,所以需要重写起初始化。

但是cell的重用是一样的

-(UITableViewCell *)tableView:(UITableView *)tableView
        cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
      UITableViewCell* uiTableViewCell= [tableView dequeueReusableCellWithIdentifier:self.nsStringIdentifier
                                                                        forIndexPath:indexPath];
      self.blockConfigureCell(uiTableViewCell,self.nsArrayModels[indexPath.row]);
    
    
    tableView.tableFooterView=[[UIView alloc] initWithFrame:CGRectZero];
    
    
    return uiTableViewCell;
}