【问题标题】:Add custom action:@selector to UISwitch on TableViewCell添加自定义操作:@selector 到 TableViewCell 上的 UISwitch
【发布时间】:2011-03-13 12:37:48
【问题描述】:

我有 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;
}

谢谢

【问题讨论】:

    标签: iphone uitableview action selector uiswitch


    【解决方案1】:

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

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

    NSIndexPath* indexPath = [theTableView indexPathForCell:theCell];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-21
      • 2018-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多