How do I retrieve UITableView row number of a UISwitch?

前端 未结 6 1139
你的背包
你的背包 2021-01-13 06:18

I have tried several approaches posted here, but I cannot get my table full of switches to return an index value for the cell of the changed switch. I am creating the view c

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-13 07:02

    You may set switch view tag to row index. Instead of theSwitch.tag = 100;

    do

    -(UITableViewCell*)tableView:table cellForRowAtIndexPath:indexPth
    {
        UISwitch *theSwitch = nil;
        if (cell == nil) {
            ...
            // as per your example
            [cell.contentView addSubview:theSwitch];
        } else {
            theSwitch = subviewWithClass(cell.contentView, [UISwitch class]);
        }
    
        theSwitch.tag = indexPath.row;
        ...
    }
    

    Add this helper function to replace viewWithTag: call

    UIView *subviewWithClass(UIView *contentview, Class klass)
    {
        for (UIView *view in contentview.subviews)
            if ([view isKindOfClass:klass])
                return view;
        return nil;
    }
    

    Then retrieve tag, that is a row index now, in your switchChanged function

    -(IBAction)switchChanged:(UISwitch *)sender {
        NSLog(@"Selected Switch - %d", sender.tag);
        ...
     }
    

提交回复
热议问题