定制UITableViewCell


第一、定制UITableViewCell的几种方式:
1.通过UITableViewCell固定格式设置,其属性是ImageView、textLabel、detailLabel,通过改变这些控件来改变位置,这种方法不够灵活
2.通过UITableViewCell的contentView属性添加子视图
3.使用UITableViewCell的xib自定义子视图,布局方便
4.子类化UITableViewCell,更加面向对象
第二、sample code:
通过UITableViewCell的contentView属性添加子视图:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil)
{
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UILabel *label=[[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)] autorelease];
label.tag=101;
[cell.contentView addSubview:label];
}
UILabel *label=(UILabel*)[cell.contentView viewWithTag:101];
NSLog(@"the clicked row is %d",indexPath.row);
label.text=[listArray objectAtIndex:indexPath.row];

return cell;
注意上述代码中先通过contentView addSubview加载子视图,为了更好地利用cell我们是在cell==nil空时,加载label,这样不用每个cell加label
使用UITableViewCell的xib自定义子视图:
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil)
{
NSArray *nibs=[[NSBundle mainBundle] loadNibNamed:@"mycell" owner:self options:nil];
cell=[nibs objectAtIndex:0];
}
UILabel *label=(UILabel*)[cell.contentView viewWithTag:101];
label.text=[listArray objectAtIndex:indexPath.row];

UIImageView *imageView=(UIImageView*)[cell.contentView viewWithTag:201];
imageView.backgroundColor=[UIColor redColor];

return cell;
第三、子类tableViewCell

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self=[super initWithStyle:style reuseIdentifier:reuseIdentifier];
if(self)
{
self.nameLabel=[[[UILabel alloc] initWithFrame:CGRectMake(0, 5, 70, 15)] autorelease];
//nameLabel.text=self.name;
[self.contentView addSubview:self.nameLabel];


self.colorLable=[[[UILabel alloc] initWithFrame:CGRectMake(0, 26, 70, 15)] autorelease];
// colorLabel.text=self.color;
[self.contentView addSubview:self.colorLable];
}
return self;
}
创建cell时采用如下函数进行实现:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier=@"SimpleTableIdentifier";

AndyTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
if(cell==nil)
{
cell=[[AndyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:identifier];

}
cell.name=[[self.listdata objectAtIndex:indexPath.row] objectForKey:@"Name"];
cell.color=[[self.listdata objectAtIndex:indexPath.row] objectForKey:@"Color"];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
return cell;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值