繁体   English   中英

在UITableview中滚动时,UiButton状态会不断变化

[英]UiButton state keeps changing when scrolling in UITableview

我知道这上面有几篇文章,但是我仍然感到困惑,为什么我在表视图中创建的按钮在被选中时不会保持其状态。 当我滚动时,未选择的按钮会受到影响,并且它会来回改变。 请帮忙。

- (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];

    }


}

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

因此,在此情况下,您正在显示Recipe A的单元格(上面有一个按钮)。 按下按钮,将更改其状态。 Recipe A离开屏幕,然后又回到屏幕上时,您将返回另一个单元格(因为使用dequeueReusableCellWithIdentifier:重复使用了表格单元格)。 对于该单元格上的按钮,正在进行两件事:

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

您需要做的是在模型中的某个位置跟踪用户“喜欢”您的哪些项(配方)。 您可以在tapped:方法的某个位置执行此操作。

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

您需要确保每次调用该方法时都执行此操作,而不仅是在if (cell == nil)块中。 顺便说一句,您是否有理由使用dequeueReusableCellWithIdentifier:而不是dequeueReusableCellWithIdentifier:indexPath 后者可从iOS 6开始使用,并保证返回一个单元格,因此, if (cell == nil)业务, if (cell == nil)无需执行此操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM