contentView tag question
I created contentViews and assigned tags. When I click row in simulator, I cannot get right tag value. Tag value is always 0. What is wrong with my code?
- (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;
[开发者_C百科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");
}
You're querying the tag of the contentview, but adding the tag to a subview of the contentview.
CellView
ContentView //You're asking for the tag of this
Subview //But assigning the tag to this
Try ((UIView*)[cell.contentview subviews] objectAtIndex:0]).tag
cell.contentView.tag returns the tag of the cell contentView but in your code, you set the tag of the subviews (image view) of contentView.
精彩评论