ios设置Cell的默认选中第一行

来源:互联网 发布:太阳系比较模拟软件 编辑:程序博客网 时间:2024/05/17 19:23

要做的需求如下图,当选到最后一行时,对选中的cell设置文字变为蓝色,右边出现☑️图标



这里介绍不需要自定义cell,相当简洁的办法,直接上代码

cellForRowAtIndexPath方法里设置

    //设置selectedBackgroundView

    cell.selectedBackgroundView = [[UIViewalloc] initWithFrame:cell.frame];

    cell.selectedBackgroundView.backgroundColor = [UIColorwhiteColor];

    //创建好选中状态需要显示的图标

    CGFloat imageViewWidth =20;

    CGFloat imageViewheight =20;

    UIImageView *selectedImageView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, w, h)];

    selectedImageView.image = [UIImageimageNamed:@"hp_sortIcon_selected"];

    selectedImageView.contentMode =UIViewContentModeScaleAspectFit;

    [cell.selectedBackgroundViewaddSubview:selectedImageView];

    //textLabel的选中状态

    cell.textLabel.highlightedTextColor = [UIColorcolorMain];


另外需要默认指定第一行时,可在添加

if (indexPath.row==0) {//指定第一行为选中状态

        [tableView selectRowAtIndexPath:indexPathanimated:NOscrollPosition:UITableViewScrollPositionNone];

    }


这样就ok了,不需要自定义cell,完全不用考虑设置当前选中cell的select状态和取消其他cell的select状态

2 0