contentView标记问题

时间:2011-08-31 16:42:14

标签: iphone

我创建了contentViews并分配了标签。当我在模拟器中单击行时,我无法获得正确的标记值。标记值始终为0。 我的代码出了什么问题?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{       
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];   

    UIImageView *imgView, *imgView1;   
    if(cell == nil)   
    {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];     
        cell.textLabel.text = @"test";

        imgView = [[UIImageView alloc] initWithFrame:CGRectMake(100,0,20,62)];
        [imgView setImage:[UIImage imageNamed:@"1.png"]];
        imgView.tag = 10;
        [cell.contentView addSubview:imgView];
        [imgView release];

        imgView1 = [[UIImageView alloc] initWithFrame:CGRectMake(200,0,20,62)];
        [imgView1 setImage:[UIImage imageNamed:@"2.png"]];
        imgView1.tag = 20;
        [cell.contentView addSubview:imgView1];
        [imgView1 release];

    }
    else
    {
        imgView = (id)[cell.contentView viewWithTag:10];
        imgView1 = (id)[cell.contentView viewWithTag:20];
    }   
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.contentView.tag == 10) // tag is always 0. What's wrong?
        NSLog(@"10");
    else if (cell.contentView.tag == 20)
        NSLog(@"20");
}

2 个答案:

答案 0 :(得分:1)

您正在查询内容视图的标记,但是将标记添加到内容视图的子视图中。

CellView
    ContentView    //You're asking for the tag of this
        Subview    //But assigning the tag to this

尝试((UIView*)[cell.contentview subviews] objectAtIndex:0]).tag

答案 1 :(得分:0)

cell.contentView.tag返回单元格contentView的标记,但在您的代码中,您设置了contentView的子视图(图像视图)的标记。