定义一个UITableViewCell的两个文件
要实现自定义的cell,一般重写两个方法(cell本身就提供了三个属性视图,所以为了避免冲突.一定不要自定义的cell的属性名和系统的冲突)
1.初始化方法
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
[self createView];
}
return self;
}
createView方法的实现:在里面只创建视图不设置尺寸,然后把属性视图放在contentView上显示
- (void)createView{
// 在里面只创建视图,不设置尺寸
self.nameLable = [[UILabel alloc] init];
self.nameLable.backgroundColor = [UIColor purpleColor];
// 把属性视图放到contentView上显示
[self.contentView addSubview:self.nameLable];
[_nameLable release];
self.phoneLable = [[UILabel alloc] init];
self.phoneLable.backgroundColor = [UIColor magentaColor];
[self.contentView addSubview:self.phoneLable];
[_phoneLable release];
self.leftImageView = [[UIImageView alloc] init];
self.imageView.backgroundColor = [UIColor grayColor];
[self.contentView addSubview:self.leftImageView];
[_leftImageView release];
self.rightImageView = [[UIImageView alloc] init];
self.rightImageView.backgroundColor = [UIColor greenColor];
[self.contentView addSubview:self.rightImageView];
[_rightImageView release];
self.midImageView = [[UIImageView alloc] init];
self.midImageView.backgroundColor = [UIColor orangeColor];
[self.contentView addSubview:self.midImageView];
[_midImageView release];
}
重写第二个方法:这个方法就是整个cell在出现前所执行的最后一个方法.所以为了能够准确的设置它的尺寸.在这个方法里写控件尺寸的设置(一定要记得重写父类的方法,不然布局会出现问题)
- (void)layoutSubviews{
// 首先需要重写父类的方法!!!!!!!!!!!!(不写布局会出现问题)
[super layoutSubviews];
// 在这个方法里只设置尺寸
self.nameLable.frame = CGRectMake(0, 0, WIDTH / 2, HEIGHT / 2);
self.phoneLable.frame = CGRectMake(WIDTH / 2, 0, WIDTH / 2, HEIGHT / 2);
self.leftImageView.frame = CGRectMake(0, HEIGHT / 2, WIDTH / 3, HEIGHT / 2);
self.midImageView.frame = CGRectMake(WIDTH / 3 , HEIGHT / 2, WIDTH / 3, HEIGHT / 2);
self.rightImageView.frame = CGRectMake(WIDTH / 3 * 2, HEIGHT / 2, WIDTH / 3, HEIGHT / 2);
}
在一个方法里写多个cell,需要更改重用标识(一个cell对应一个标识)- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row % 2 == 0) {
static NSString *reuse = @"myCell";
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
if (!cell) {
cell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse] autorelease];
}
NSDictionary *dic = self.stuArr[indexPath.row];
cell.nameLable.text = dic[@"name"];
cell.phoneLable.text = dic[@"phone"];
cell.leftImageView.image = [UIImage imageNamed:@"3.jpg"];
cell.rightImageView.image = [UIImage imageNamed:@"3.jpg"];
cell.midImageView.image = [UIImage imageNamed:@"3.jpg"];
return cell;
} else {
// 必须更改重用标识(一个cell对应一个标识)
static NSString *manCell = @"manCell";
ManCell *cell = [tableView dequeueReusableCellWithIdentifier:manCell];
if (!cell) {
cell = [[[ManCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:manCell] autorelease];
}
return cell;
}
}
8738

被折叠的 条评论
为什么被折叠?



