代码之家  ›  专栏  ›  技术社区  ›  Borut Tomazin

添加自定义action:@selector 打开TableViewCell

  •  6
  • Borut Tomazin  · 技术社区  · 14 年前

    我有TableCellViewController用于管理UITableView中的单元格。每个单元格都有一个标签na ui开关(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的状态,我必须获取这个单元格的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;
    }
    

    1 回复  |  直到 14 年前
        1
  •  4
  •   kennytm    14 年前

    你可以用UISwitch的 .tag property

    NSIndexPath* indexPath = [theTableView indexPathForCell:theCell];