Search code examples
iosobjective-cuitableviewuitableviewrowaction

How select one item at a time ios sdk


I have a list of Option values displayed in a UITableView.

Now I want user to select one item once. But currently the user can select all the option.

What I want :

Suppose I Have 5 radio boxes : 1 2 3 4 5 at a time user can only select one . If he choses another one then Previous one must get deselected.

What is Happening Now:

Currently all of the boxes are get selected.

I am using this code in my didSelectRowAtIndex method:

 UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
 UIButton *btnRadhio = (UIButton *)[cell viewWithTag:1];

 for(int i =0;i<[arrDistanceList count];i++)
   {
     [btnRadhio setBackgroundImage:[UIImage imageNamed:@"radio_unchecked"] forState:UIControlStateNormal];
   }

    [btnRadhio setBackgroundImage:[UIImage imageNamed:@"radio_checked"] forState:UIControlStateNormal];

Solution

  • You are changing the UIButton for same index path:

      UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; //From Your Code
    

    You have to get new indexPath each time. Try this one

      for(int i =0;i<[arrDistanceList count];i++)
    {
        NSIndexPath *indexPathI=[NSIndexPath indexPathForRow:i inSection:0]; //i supposed you have 0 section
        UITableViewCell *cellI=[tableView cellForRowAtIndexPath:indexPathI];
        UIButton *btnRadhio = (UIButton *)[cellI viewWithTag:1];
        if(i==indexPath.row)
        {
            [btnRadhio setBackgroundImage:[UIImage imageNamed:@"radio_checked"] forState:UIControlStateNormal];
        }
        else
        {
            [btnRadhio setBackgroundImage:[UIImage imageNamed:@"radio_unchecked"] forState:UIControlStateNormal];
        }
    }
    

    You can check here also