如何通过单击单元格的子视图获取UITableViewCell的indexPath - 获取不兼容的指针类型警告

Ken*_*ili 5 objective-c uitableview ios

我正在向contentView添加一个开关,而contentView属于该单元格.我正在尝试获取触发开关的单元格的行号.

这是代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MainCell"];
    }

    UISwitch *theSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
    [cell addSubview:theSwitch];
    cell.accessoryView = theSwitch;
    [theSwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];

    return cell;
}

- (void) switchChanged:(UISwitch *)sender {
    UITableViewCell *theParentCell = [[sender superview] superview]; // Throwing Warning here 
    NSIndexPath *indexPathOfSwitch = [mainTableView indexPathForCell:theParentCell];
    NSLog(@"the index path of the switch: %ld", (long)indexPathOfSwitch.row);
}
Run Code Online (Sandbox Code Playgroud)

这是警告信息:

警告:"不兼容的指针类型使用UIView*类型的表达式初始化UITableViewCell*"

发件人应该是什么而不是superview?

moh*_*acs 4

如果我理解正确的话,您正在尝试获取切换父单元格索引。

-(NSIndexPath *)indexPathWithSubview:(UIView *)subview {
    while (![subview isKindOfClass:[UITableViewCell self]] && subview) {
        subview = subview.superview;
    }
    return [self.mytable indexPathForCell:(UITableViewCell *)subview];
}

- (void) switchChanged:(UISwitch *)sender {
    NSIndexPath *apath = [self indexPathWithSubview:(UISwitch *)sender];
}
Run Code Online (Sandbox Code Playgroud)