IOS 学习:UITableView使用详解2 自定义的单元格

IOS 学习:UITableView使用详解2 自定义的单元格

1.建立CustomCell类

使用常见的建立类的方法,把被继承的类设置为UITableViewCell。

建立了类之后再次点击新建文件,选择CocoaTouch 下的empty,建立一个nib文件,

讲一个表格单元格Table View Cell控件拖进nib视图,添加,image view 和三个textLabel进来。如下图所示:

将该单元格的class设置为CustomCell。

属性当中的Identifier设置为CustomCellIdentifier待会要用到这个属性。

在CustomCell.m文件里面添加输出口,如下图所示:

点击nib文件,建立好连线。

在该头文件当中添加属性:

想要将这些属性用来改变便签和图片视图,则必须必须使用自定义set方法,当使用点运算符进行赋值时,自动调用set方法,因此在CustomCell.m中添加以下set方法:

- (void)setImage:(UIImage *)img {

    if (![img isEqual:image]) {

        image = [img copy];

        self.imageView.image = image;

    }

}

-(void)setName:(NSString *)n {

    if (![n isEqualToString:name]) {

        name = [n copy];

        self.nameLabel.text = name;

    }

}

-(void)setDec:(NSString *)d {

    if (![d isEqualToString:dec]) {

        dec = [d copy];

        self.decLabel.text = dec;

    }

}

-(void)setLoc:(NSString *)l {

    if (![l isEqualToString:loc]) {

        loc = [l copy];

        self.locLabel.text = loc;

    }

}

这样CustomCell类就配置完毕了。

2.使用CustomCell

在ViewController当中添加,import”CustomCell.h”,添加好数据源和UITableView的委托方法。这和一般的建表方法差不多,有区别的方法如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    staticNSString *CustomCellIdentifier = @"CustomCellIdentifier";//

    

    staticBOOL nibsRegistered = NO;//添加nib文件注册

    if (!nibsRegistered) {

        UINib *nib = [UINibnibWithNibName:@"CustomCell"bundle:nil];

        [tableView registerNib:nib forCellReuseIdentifier:CustomCellIdentifier];//注册nib文件

        nibsRegistered = YES;

    }

    

    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];//单元格重用

    if (cell == nil) { //如果没有可重用的单元格,则新建一个单元格。

        cell = [[CustomCellalloc

                initWithStyle:UITableViewCellStyleDefault 

                reuseIdentifier:CustomCellIdentifier]; 

    }

     NSUInteger row = [indexPath row];

     NSDictionary *rowData = [self.dataListobjectAtIndex:row];

    

     cell.name = [rowData objectForKey:@"name"];

     cell.dec = [rowData objectForKey:@"dec"];//使用点运算符赋值,自动调用set方法,实现标签和图片的更改。

     cell.loc = [rowData objectForKey:@"loc"];

     cell.image = [imageListobjectAtIndex:row];

     

    return cell;

}

如此这般,自定义的单元格就建立完毕。

原文地址:https://www.cnblogs.com/jackwuyongxing/p/3519628.html