我有一個包含圖像和按鈕的表格。每個按鈕都有一個帶有不同編號的標籤。單擊時所有按鈕執行相同的方法。我將在他們運行的方法上使用按鈕的標記,以瞭解哪個按鈕被點擊。IPHONE:單元格上的UITableView按鈕報錯標籤
問題是被報告的按鈕標籤是錯誤的。我想象當細胞被重複使用時,某些東西會干擾標籤。
這是我使用的填充在飛行表的代碼:
- (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;
}
這就是百腦匯方法...
- (void) buyNow:(id)sender {
int index = [sender tag];
NSLog(@"button clicked = %d", index);
}
該按鈕是報告爲點擊從0到6的一個週期,沒有報道超過6的數字。我認爲這與細胞被重複使用相對應,爲什麼這個數字沒有變化,是一個謎。
如何解決?
感謝您的任何幫助。
如果您不重複使用單元格,它會起作用嗎? – Tim 2009-10-21 00:38:57