iOS自定义单元格之手动编码

记录一个菜鸟的iOS学习之旅,如能帮助正在学习的你,亦枫不胜荣幸;如路过的大神如指教几句,亦枫感激涕淋!

iOS自定义单元格之手动编码_第1张图片

在前面两篇文章中,亦枫简单的介绍了通过故事板和xib文件自定义单元格来创建简单的表视图。本文就以一段代码为例介绍第三种自定义单元格的方式 —— 手动编码。

还是以之前创建简单表视图的代码为例,我们创建自定义单元格类Custom.h和Custom.m文件,只不过不关联xib文件。

Custom.h头文件代码如下,只是创建了一个文本控件的输出口:

#import 

@interface CustomCell : UITableViewCell

@property IBOutlet UILabel *titleLabel;

@end

Custom.m实现文件如下,我们重写了父类UITableViewCell中的 initWithStyle: reuseIdentifier: 方法,并通过 initWithFrame: 方法创建了一个UILabel对象:

#import "CustomCell.h"

@implementation CustomCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 160, self.frame.size.height)];
        _titleLabel.text = @"111111111";
        [self.contentView addSubview:_titleLabel];
        
        
    }
    return self;
}

@end

然后在 ViewController.m 视图控制器中,在 tableView: cellForRowAtIndexPath: 方法里面创建单元格对象,并通过调用对象的 initWithStyle: reuseIdentifier: 方法进行初始化:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
    if (cell==nil) {
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CustomCell"];
    }
    NSInteger rowIndex = [indexPath row];
    NSDictionary *cellDictionary = [self.simpleData objectAtIndex:rowIndex];
    cell.titleLabel.text = [cellDictionary objectForKey:@"name"];

    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    return cell;
}

运行效果如下:

iOS自定义单元格之手动编码_第2张图片
效果图.png

这里只是简单地介绍流程,至于如何通过代码设计好看的单元格,在后续实例中另行讲解。

关于initWithFrame方法

最后顺便介绍一下上面提到的initWithFrame方法。

在创建UI视图对象时,我们需要自己手动调用 initWithFrame: 方法,根据参数指定的尺寸——CGRect来初始化并返回一个新的视图对象。

与之不同的是initWithCoder 方法,当视图来源于xib文件,即通过在interface builder中拖拽视图控件时,在加载的时候,系统会自动调用 initWithCode 方法。

你可能感兴趣的:(iOS自定义单元格之手动编码)