2009-10-21 5 views
0

이미지와 단추가 포함 된 표가 있습니다. 각 버튼마다 다른 번호의 태그가 있습니다. 모든 버튼은 클릭 할 때 동일한 방법을 실행합니다. 클릭 한 단추를 알기 위해 단추의 태그를 실행하는 메서드에 사용합니다.IPHONE : 잘못된 태그를보고하는 셀의 UITableView 단추

문제는보고되는 버튼의 태그가 잘못되었습니다. 세포가 재사용됨에 따라 무언가가 태그를 방해하고 있다고 생각합니다. 버튼의 존재

- (void) buyNow:(id)sender { 

    int index = [sender tag]; 

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

...

- (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 방법입니다 :

이것은 내가 즉석에서 테이블을 채우는 데 사용하고있는 코드는 0에서 6까지 클릭 한 주기로보고되면 6을 넘는 숫자는보고되지 않습니다. 나는 이것이 재사용되는 세포에 해당한다고 생각한다. 왜 숫자가 변하지 않는지는 수수께끼이다.

어떻게 해결할 수 있습니까?

도움을 주셔서 감사합니다.

+0

세포를 재사용하지 않으면 작동합니까? – Tim

답변

2

생성하고 버튼을 설정하고 willDisplayCell 방법으로 셀에 추가 코드를 이동해보십시오 :

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

나는 이것이 당신이 세포를 재사용하고 또한의 고유 한 인스턴스를 가질 수 있도록 생각을 버튼을 하나씩 누릅니다.

+0

감사합니다! 그게 다야! 당신은 D 남자입니다! – SpaceDog

관련 문제