第一、定制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;
}
定制UITableViewCell
最新推荐文章于 2016-03-12 00:31:44 发布