UITableViewCell的accessoryType属性复用

    xiaoxiao2023-06-01  1

    今天在写程序时,在写一个tableView的选中状态为UITableViewCellAccessoryCheckmark,发现第一行变为checkmark后,滑到最后一行也变为checkmark状态,想了想,是cell的复用问题,当选中第一行后,cell的accessType类型已经为checkmark,滑到最后,cell复用,取已经生产成的第一行cell展示出来,所以显示时已经标记了。一开始解决的思路是大不了判断一下,及当复用的cell出现if(cell== nil || cell.accessoryType == UITableViewCellAccessoryCheckmark) 时再重新创建一个cell,不与之前的cell复用了,这种判断方式忽略了UITableViewCell *cell = [tableVie dequeueReusableCellWithIdentifier:identifyOfTableViewCell];根本不走if(cell ....)了,因为cell直接取出,已经申请好了,走不通。又想采用迂回战术吧,申请了一个,数组,当选中cell时,判断选中的cell是否已经选中,选中把indexPath加紧数组,取消选中从数组中删除,再在cellForRow方法中判断数组中是否有选中的indexPath,在判断前要让cell的选中状态为UITableViewCellAccessoryNO,有选中的indexPath就cell.accessoryType = UITableViewCellAccessoryCheckmark。 在此处的数组换成集合比较好,防止数组越界引起的崩溃。

    代码:

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

    {

            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifyOfTableViewCell];

            if(cell == nil){

                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifyOfTableViewCell];

            }

            cell.accessoryType = UITableViewCellAccessoryNone; //要写在if判断语句外

            if ([self.mainSaleSet containsObject:indexPath]) {

                

                cell.accessoryType = UITableViewCellAccessoryCheckmark;

            }

            cell.textLabel.highlightedTextColor = [UIColor blueColor];

            cell.textLabel.text = _mainSaleArray[indexPath.row];

            return cell;

      }

    -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

    {

    if (tableView == _mainScaleTableView) {

            UCLog(@"点击_mainScaleTableView");

            //判断cellaccesstype状态

            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

            if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {

                cell.accessoryType = UITableViewCellAccessoryNone;

                [self.mainSaleSet removeObject:indexPath];

            }else if (cell.accessoryType == UITableViewCellAccessoryNone){

                cell.accessoryType = UITableViewCellAccessoryCheckmark;

                [self.mainSaleSet addObject:indexPath];

            }

            

     }       

        }

    转载请注明原文地址: https://ju.6miu.com/read-1262208.html
    最新回复(0)