在TableViewCell上添加自定义操作:@selector到UISwitch

Bor*_*zin 6 iphone action selector uitableview uiswitch

我有TableCellViewController来管理我的UITableView中的单元格.每个单元格都有一个标签na UISwitch(dictTypeSwitch).想要分配方法来切换事件,这样我就可以保存按钮的状态.

到目前为止我已经这样做了:

将setState函数赋给object:

[cell.dictTypeSwitch addTarget:self action:@selector(setState:) forControlEvents:UIControlEventTouchUpInside];
Run Code Online (Sandbox Code Playgroud)

处理事件的功能:

- (void)setState:(id)sender {
    BOOL state = [sender isOn];
    NSString *rez = state == YES ? @"YES" : @"NO";
    NSLog(rez);
}
Run Code Online (Sandbox Code Playgroud)

从发件人我得到UISwitch对象,我可以从中获得状态.

到目前为止一切都很好.

但是如果我想保存UISwitch的状态,我必须得到这个单元格的rowIndex.我怎样才能做到这一点?

The cells are made inside function cellForRowAtIndexPath. Se the code bellow:

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"DictionariesTableCellViewController";
    DictionariesTableCellViewController *cell = (DictionariesTableCellViewController *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];


        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"DictionariesTableCellViewController" owner:nil options:nil];

        for (id currentObject in topLevelObjects) {
            if ([currentObject isKindOfClass:[UITableViewCell class]]) {
                cell = (DictionariesTableCellViewController *) currentObject;
                break;
            }
        }
    }

    // Configure the cell...

    cell.dictTypeLabel.text = [NSString stringWithFormat:@"row - %i",indexPath.row];
    [cell.dictTypeSwitch addTarget:self action:@selector(setState:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}
Run Code Online (Sandbox Code Playgroud)

谢谢

ken*_*ytm 4

您可以使用 UISwitch 的.tag属性来存储任意整数。这可以设置为行索引。

如果可以从 UISwitch 的父级找到 UITableViewCell,则可以使用以下命令获取索引路径

NSIndexPath* indexPath = [theTableView indexPathForCell:theCell];
Run Code Online (Sandbox Code Playgroud)