IPHONE:单元格上的UITableView按钮报告错误标记

时间:2009-10-21 00:16:31

标签: iphone iphone-sdk-3.0

我有一张包含图像和按钮的表格。每个按钮都有一个不同编号的标签。单击时,所有按钮都执行相同的方法。我将在他们运行的方法上使用按钮的标签,以了解单击了哪个按钮。

问题是报告的按钮标签是错误的。我想,随着细胞被重复使用,有些东西会干扰标签。

这是我用来动态填充表格的代码:

  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = @"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                   reuseIdentifier:MyIdentifier] autorelease];

    UIButton *buyButton = [[UIButton alloc] initWithFrame:CGRectMake( 220, 4, 100, 35)];

    buyButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    buyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [buyButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    buyButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [buyButton setBackgroundImage:newImage forState:UIControlStateNormal];
    [buyButton addTarget:self action:@selector(buyNow:) forControlEvents:UIControlEventTouchDown];
    [buyButton setTag: 1]; // I have to do this, to locate the button a few lines below
    [cell addSubview:buyButton];
    [buyButton release];
}


 imageU = [[[UIImage alloc]initWithContentsOfFile:[[NSBundle mainBundle] 
                              pathForResource:[NSString stringWithFormat: @"table-pg%d",numberX] 
                                                    ofType:@"jpg"]] autorelease];
    cell.imageView.image = imageU;

    UIButton * myButton = (UIButton *) [cell viewWithTag:1];        
    [myButton setTitle:NSLocalizedString(@"buyKey", @"") forState:UIControlStateNormal]; 

    UIImage *newImage = [[[[UIImage alloc]initWithContentsOfFile:[[NSBundle mainBundle] 
                                             pathForResource: @"whiteButton" ofType:@"png"]] autorelease]
                                                     stretchableImageWithLeftCapWidth:12.0f topCapHeight:0.0f];

    [buyButton setTag:indexPath.row]; // the button's tag is set here

return cell;

}

这是buyNow方法......

- (void) buyNow:(id)sender {

    int index = [sender tag];

    NSLog(@"button clicked = %d", index);
}

按钮被报告为点击的按钮从0到6循环,没有报告超过6的数字。我认为这对应于重复使用的细胞,为什么数字不会改变,这是一个谜。

如何解决?

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

尝试移动创建并设置按钮的代码,并将其添加到willDisplayCell方法的单元格中:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

我认为这将允许您重复使用单元格,并且每个单元格中都有一个唯一的按钮实例。

相关问题