dequeueReusableCellWithIdentifier更改多个UIPickerviews值

时间:2016-04-06 11:08:37

标签: ios objective-c uitableview uipickerview

我正在创建一个具有pickerView的自定义单元格,当我运行应用程序时,它会使用选择器视图加载所有单元格。一次可以看到4个单元格,当我更改第一个选择器视图的值并向下滚动时。每四个选择器的价值都已改变。我得到所有选择器视图的值,它返回正确的值,意味着它只更改第一个选择器视图的值。

-(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; }

3 个答案:

答案 0 :(得分:2)

这种情况正在发生,因为正在重复使用该单元但从未重置选择器。

配置单元格进行显示时,需要先将选择器设置为默认值,然后再将其设置为该单元格的正确值(如果适用)。

您需要将选择器中选择的值存储在表格单元格以外的某个位置。表单元格将被重用,因此您需要一个数据结构(可能是您的数据源)。

答案 1 :(得分:0)

中为每个单元格设置选择器视图值
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

如果您没有为每个单元格设置它,那么选择器视图值将会很奇怪。它在滚动后显示相同值的原因是因为iOS只是拾取可见单元格并在滚动时再次显示它们。因此,除非您在cellForRowAtIndexPath:中设置值,否则它们将具有先前的值。

答案 2 :(得分:0)

浪费了6个小时后,我解决了问题,这是更新后的代码:

-(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;
}
相关问题