• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

iOSUITableView自定义cell

武飞扬头像
瓯海剑
帮助1

在我们使用UITableView时,常常会遇到系统提供的样式无法满足项目需求的时候,这时需要我们根据需求自定义cell

注册与非注册

注册

注册主要是在获取复用的cell时,如果没有可复用的cell,系统将会自动的使用注册时提供的类来创建可用的cell,这样确保了返回的一定是可用的cell。

[_tableView registerClass:[MessageCell class] forCellReuseIdentifier:@"cell"];

MessageCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

非注册

非注册时就需要判断返回的cell是否为空,如果为空,则为它创建一个新的cell。

    UITableViewCell* cell = [_tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if(cell == nil) {
        cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    }

代码自定义cell:

  1. 新建一个继承自UITableViewCell的类,为该类添加我们需要的属性
@interface MessageCell : UITableViewCell

// 基本数据
@property (nonatomic, weak) UILabel* userName;
@property (nonatomic, weak) UILabel* message;

@end
  1. 重写- (instancetype) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier方法
  • 添加我们需要显示的子控件
  • 为子控件某些不变的属性(如字体)进行设置
- (instancetype) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        UILabel* userName = [[UILabel alloc] init];
        userName.font = nameFont;
        [self.contentView addSubview:userName];
        self.userName = userName;
        
        UILabel* message = [[UILabel alloc] init];
        message.font = messageFont;
        [self.contentView addSubview:message];
        self.message = message;
    }
    return self;
}
  1. 实现TableView的数据源方法返回我们自定义的cell
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString* cellStr = @"cell";
    
    MessageCell* cell = [_tableView dequeueReusableCellWithIdentifier:cellStr];
    
    if (cell == nil) {
        cell = [[MessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellStr];
    }
    
    /* 传递数据给cell */
    
    return cell;
}
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgaakkj
系列文章
更多 icon
同类精品
更多 icon
继续加载