Search code examples
iosobjective-cuitableviewuiswitch

UISwitch off state is not stable while scrolling in tableview


I'm creating a UISwitch programmatically in one of the tableview datasource function(cell for row at index). when I'm scrolling the table view, the OFF state switches are malfunctioned(UI) two rounds appeared. Attaching the screenshot of the switch.enter image description here

Appreciate your help!

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    UILabel *title = (UILabel*)[cell viewWithTag:80];
    UILabel *description = (UILabel*)[cell viewWithTag:81];
    UIView *innerView = (UIView *)[cell viewWithTag:82];

    innerView.layer.borderColor=[[UIColor colorWithRed:229/255.0f green:229/255.0f blue:229/255.0f alpha:1.0]  CGColor];
    innerView.layer.borderWidth = 2.0f;
    NSDictionary *displayDict = scenarioListsArray[indexPath.row];
    title.text =[displayDict objectForKey:@"name"];
    description.text = [displayDict objectForKey:@"description"];    
    UISwitch *myswitch = [[UISwitch alloc]initWithFrame:CGRectMake(cell.contentView.frame.size.width-60, (cell.contentView.frame.size.height/2)-20 , 100, 100)];
    myswitch.onTintColor = [UIColor colorWithRed:25/255.0f green:122/255.0f blue:66/255.0f alpha:1];
    [cell.contentView addSubview:myswitch];
    myswitch.tag = indexPath.row;
    [myswitch addTarget:self action:@selector(cellButtonClickAction:) forControlEvents:UIControlEventValueChanged];
    if ([[displayDict objectForKey:@"status"] isEqualToString:@"ACTIVE"]) {
        [myswitch setOn:YES animated:YES];

    }
    else
    {
        [myswitch setOn:NO animated:YES];
    }


    return cell;
}

Solution

  • I have faced the same issue and fixed with following code before creating switch

    for(UIView *subView in cell. contentView.subviews){
            if ([subView isKindOfClass:[UISwitch class]]) {
            [subView removeFromSuperview];
    
        }
        }
    

    Or

    static NSString *TableIdentifier = @"YourCellIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableIdentifier];
    
    if (cell == nil) {
         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableIdentifier];
        //place your all UI elements code here.
      }