6

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

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

将 setState 函数分配给对象:

[cell.dictTypeSwitch addTarget:self action:@selector(setState:) forControlEvents:UIControlEventTouchUpInside];

事件处理函数:

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

从发件人那里我得到 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;
}

谢谢

4

1 回答 1

4

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

如果可以从 UISwitch 的父级中找到 UITableViewCell,则可以使用

NSIndexPath* indexPath = [theTableView indexPathForCell:theCell];
于 2010-07-08T18:56:05.510 回答