0

I know there are a few posts abou this but I am still confused why the button i created in a tableview wont keep its state when its selected. When I scroll, unselected buttons get affected and it changes back and forth. Please help.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    static NSString *simpleTableIdentifier = @"SimpleTableCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
        UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [myButton setTitle:@"Like" forState:UIControlStateNormal];
        [myButton addTarget:self action:@selector(tapped:) forControlEvents:UIControlEventTouchUpInside];
        myButton.frame = CGRectMake(14.0, 10.0, 125.0, 25.0);
        myButton.tag =indexPath.row;
        [cell.contentView addSubview:myButton];



    }
    else{
        [cell.contentView addSubview:myButton];

    }
 if ([array objectAtIndex:indexPath.row==0]) {
        [myButton setTitle:@"Like" forState:UIControlStateNormal];

    }
    else{
        [myButton setTitle:@"Unlike" forState:UIControlStateNormal];


    }


    cell.textLabel.text = [recipes objectAtIndex:indexPath.row];

    return cell;
}


-(void)tapped:(UIButton *)sender {

    if ([sender.currentTitle isEqualToString:@"Like"]) {
        [sender setTitle:@"Unlike" forState:UIControlStateNormal];
[array replaceObjectAtIndex:sender.tag withObject:[NSNumber numberWithInt:1]];
    }
    else{
        [sender setTitle:@"Like" forState:UIControlStateNormal];

    }


}
4

1 回答 1

0

帮助您了解为什么会发生这种情况;每次在表格视图的屏幕上显示行的单元格时tableView:cellForRowAtIndexPath:,都会调用您的方法来检索将显示的单元格。也就是说,当第一次显示单元格时,会调用此方法。然后,如果此单元格离开屏幕,然后再次回到屏幕上,则将再次调用此方法以设置和检索单元格。

因此,在您的情况下,您正在显示一个单元格(上面有一个按钮)Recipe A。按下按钮,这会改变它的状态。当Recipe A离开屏幕,然后又回到屏幕上时,您会返回一个不同的单元格(因为表格单元格与 一起重复使用dequeueReusableCellWithIdentifier:)。对于该单元格上的按钮,发生了两件事:

  • 第一次使用时,单元格上已经有一个按钮(可能用于不同的配方)。您没有告诉它是否应该处于“喜欢”或“不喜欢”状态Recipe A
  • 您向单元格添加了另一个按钮,但实际上并未设置其框架/标题,因此您实际上不会以任何方式看到它。

您需要做的是在您的模型中某处跟踪用户“喜欢”了您的哪些项目(食谱)。你会在你的tapped:方法中的某个地方这样做。

然后,在您的tableView:cellForRowAtIndexPath:方法中,您需要将按钮设置为该行/食谱的适当状态(“喜欢”与否)。

您需要确保每次调用方法时都这样做,而不仅仅是在您的if (cell == nil)块中。顺便说一句,您使用dequeueReusableCellWithIdentifier:而不是有原因dequeueReusableCellWithIdentifier:indexPath吗?后者从 iOS 6 开始可用,并且保证返回一个单元格,所以你不需要做这个if (cell == nil)业务。

于 2014-08-10T08:57:40.580 回答