我有一个包含图像和按钮的表。每个按钮都有一个不同编号的标签。单击时,所有按钮执行相同的方法。我将在它们运行的方法上使用按钮的标记,以了解单击了哪个按钮。
问题是正在报告的按钮标签错误。我想象当这些单元被重用时,有什么东西干扰了标签。
这是我用来动态填充表的代码:
- (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的数字被报告。我认为这与被重用的细胞相对应,为什么数字不变,是个谜。
如何解决这个问题?
谢谢你的帮助。