CustomCell 中的 UISwitch 未更改特定索引路径处的值

UISwitch in CustomCell is not changing the value at specific indexpath

这是我制作的屏幕类型:
因此,当 UISwitch 状态发生变化时,它应该将标签更改为 ONOFF。在我的 cellForRowAtIndexPath 中,我调用 [cell.mainSwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged]; 并且 switchChanged 如下:

-(void) switchChanged:(id)sender {
    UISwitch* cellNew = (UISwitch*)sender;

        if ([cellNew isOn]) {
            cell.funcStatus.text = [funcStatusArr objectAtIndex:0];
        } else {
            cell.funcStatus.text = [funcStatusArr objectAtIndex:1];
        }
}

现在我面临的问题是它没有更改特定单元格的 Label 但所有开关都在更改第 4 个(最后一个)单元格的标签,如下图所示。
如您所见,第一个标签已关闭,但它正在更改最后一行的标签。任何想法为什么会发生或如何告诉函数这个 index.row 正在发送请求。

所以你必须将 tag 属性 添加到所有 UISwitch。更快的方法是在 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 调用

 // code
 // its good work if u have only 1 section
 mySwitch.tag = indexPath.row.
 //code 

比修复你的代码

-(void) switchChanged:(UISwitch*)switch {
    SettingsTableViewCell *selectedCell;
    NSIndexPath *selectedIndexPath;
    if(switch.tag == 0)
      // create selectedIndexPath with correctrly row and section
       selectedIndexPath = [NSIndexPath indexPathForRow:'YourRow'inSection:'Your section']
      // create cell
       selectedCell = [self.tableView cellForIndexPath:selectedIndexPath];
     } else if(switch.tag == 1) {
      // same logic;
     }

    // and replace text for selected cell
    if ([switch isOn]) {
        selectedCell.funcStatus.text = [funcStatusArr objectAtIndex:0];
    } else {
        selectedCell.funcStatus.text = [funcStatusArr objectAtIndex:1];
    }
}

一定有用。

你做错了thing.First你需要在特定的更改事件中获取单元格。 请遵循此代码。

-(void) switchChanged:(id)sender {



    UISwitch* switchBtn = (UISwitch*)sender;
    //self.tableView is UITableView's outlet named tableView
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    //First detect Tableview's Cell then do the stuff
    //CustomCellTableViewCell replace it with you custom cell class
    CustomCellTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];

    if ([switchBtn isOn]) {
        cell.funcStatus.text = [funcStatusArr objectAtIndex:0];
    } else {
        cell.funcStatus.text = [funcStatusArr objectAtIndex:1];
    }
    [self.tableView reloadRowsAtIndexPaths:[[NSArray alloc] initWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];


}

干杯。