Search code examples
iosobjective-cuitableviewuipickerview

dequeueReusableCellWithIdentifier change multiple UIPickerviews Value


I am creating a custom cell which have pickerView, when I run the app it loads all cells with picker view. At a time 4 cells are visible, When i change the value of first picker view and scroll down. Value of every 4th picker has been changed. I get the values of all picker views, it returns correct value, means it only changes the value of first picker view.

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

     AddTaskTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"addTaskCell" forIndexPath:indexPath];

    AddTaskDetails *task =[self.tasksArray objectAtIndex:indexPath.row];
    NSAttributedString *attributedString = [self attributedTextForTask:task.taskDetail];
    cell.taskDetails.attributedText = attributedString;
    cell.hourePicker.tag = indexPath.row;
    [cell.hourePicker selectRow:0 inComponent:0 animated:YES];
    cell.addDescriptionBtn.tag = indexPath.row;

    [cell.addDescriptionBtn addTarget:self action:@selector(didTapAddDescButton:) forControlEvents:UIControlEventTouchUpInside];

    return  cell; }

Solution

  • After wasting 6 hours, I have solved the problem and here is the updated code:

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    
         AddTaskTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"addTaskCell" forIndexPath:indexPath];
    
        AddTaskDetails *task =[self.tasksArray objectAtIndex:indexPath.row];
        NSAttributedString *attributedString = [self attributedTextForTask:task.taskDetail];
        cell.taskDetails.attributedText = attributedString;
        cell.hourePicker.tag = indexPath.row;
    
        cell.addDescriptionBtn.tag = indexPath.row;
    
        [cell.addDescriptionBtn addTarget:self action:@selector(didTapAddDescButton:) forControlEvents:UIControlEventTouchUpInside];
        AddTaskDetails *task_1 =[self.tasksArray objectAtIndex:indexPath.row];
        if(task_1.hours>0)
        {
           [cell.hourePicker selectRow:task_1.hours inComponent:0 animated:NO];
        }
        else
        {
             [cell.hourePicker selectRow:0 inComponent:0 animated:NO];
        }
    
        return  cell;
    }