防止cell里面的子控件重叠方法

来源:互联网 发布:2017淘宝有多少家店铺 编辑:程序博客网 时间:2024/05/21 10:24

有时候。我们没有自定义cell的时候,我们需要给uitableview自带的cell里面添加一些控件。比如我往cell里面再加入一个uilabel和一个iconview。

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{      static NSString *identifier=@"moreiden";      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];      if (cell==nil) {          cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault       reuseIdentifier:identifier];          [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];      }      //这里开始加入两个控件        UIImageView *iconview=[[UIImageView alloc]init];        //设置圆角        iconview.layer.masksToBounds=YES;        iconview.layer.cornerRadius=30/2;        iconview.frame=CGRectMake(50, 15, 30, 30);//随便定的位置        [iconview setImage:[UIImage imageNamed:@"tupian.png"]];        [cell.contentView addSubview:iconview];        UILabel *textlab=[[UILabel alloc]init];        textlab.text=@"我是新加进来的label";        textlab.font=[UIFont systemFontOfSize:12];        textlab.textColor=[UIColor blackColor];        textlab.frame=CGRectMake(100, 10, 80, 30);//随便定的位置        [cell.contentView addSubview:textlab];        return cell;}

这样,每次cell里面不仅仅有自己的一些子控件,还有一些我们加入的子控件,可是问题来了。如果这个页面没有在切换时销毁,那么每次我们切换页面的时候,cell里面就会每次都加两个子控件,而且位置都一样,这样来回切换几次,会发现我们的cell里面加入的那些子控件已经重叠变形了。如果我们打开断点会发现,每次切换时,cell.contentView.subviews.count就会增加两个。怎么办呢。这时候,我们就需要在每次往cell里面加东西时,做一次遍历,把之前加入的控件都删掉就行了。

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{      static NSString *identifier=@"moreiden";      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];      if (cell==nil) {          cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault       reuseIdentifier:identifier];          [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];      }         //防止每次切换页面都往cell添加子空间,造成重叠        for (id subview in cell.contentView.subviews) {            [subview removeFromSuperview];        }      //这里开始加入两个控件        UIImageView *iconview=[[UIImageView alloc]init];        //设置圆角        iconview.layer.masksToBounds=YES;        iconview.layer.cornerRadius=30/2;        iconview.frame=CGRectMake(50, 15, 30, 30);//随便定的位置        [iconview setImage:[UIImage imageNamed:@"tupian.png"]];        [cell.contentView addSubview:iconview];        UILabel *textlab=[[UILabel alloc]init];        textlab.text=@"我是新加进来的label";        textlab.font=[UIFont systemFontOfSize:12];        textlab.textColor=[UIColor blackColor];        textlab.frame=CGRectMake(100, 10, 80, 30);//随便定的位置        [cell.contentView addSubview:textlab];        return cell;}

ok ,大功告成!

1 0