美文网首页
ios ~ UITableView 中,cell赋值方法中cel

ios ~ UITableView 中,cell赋值方法中cel

作者: 阳光下的叶子呵 | 来源:发表于2022-03-31 16:41 被阅读0次

    需求:在cellForRowAtIndexPath中直接创建其他view时,因为没有使用重用机制,为防止会创建多个view可以这样:

    以下两个UIview只能同时存在一个,所以,相同的view时,不创建新的,不同的view时,需要将前一个view删掉,再创建新的下一个view

    // 删掉tag为“1235”的view:

           [[cell.contentView viewWithTag:1235] removeFromSuperview];
    

    // 删掉tag为“1234”的view:

           [[cell.contentView viewWithTag:1234] removeFromSuperview];
    

    代码:

    - (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
        if(!cell){
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
            }
        cell.backgroundColor = UIColor.clearColor;
        cell.contentView.backgroundColor = UIColor.clearColor;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    
        if (self.gameListDataSource.count > 0) { // 是否 > 0
            GameSectionView *addGeamView = [cell.contentView viewWithTag:1234]?[cell.contentView viewWithTag:1234]:[[GameSectionView alloc]init];
            addGeamView.tag = 1234;
           [cell.contentView addSubview:addGeamView];
            [addGeamView mas_makeConstraints:^(MASConstraintMaker *make) {
                            make.edges.equalTo(cell.contentView);
           }];
            // 删掉tag为“1235”的view
           [[cell.contentView viewWithTag:1235] removeFromSuperview];
        } else {
                        
            NotGameView *notGameHeaderView = [cell.contentView viewWithTag:1235]?[cell.contentView viewWithTag:1235]:[[NotGameView alloc] init];
            notGameHeaderView.tag = 1235;
            [cell.contentView addSubview:notGameHeaderView];
            [notGameHeaderView makeConstraints:^(MASConstraintMaker *make) {
                 make.edges.equalTo(cell.contentView);
            }];
            // 删掉tag为“1234”的view
            [[cell.contentView viewWithTag:1234] removeFromSuperview];
        }
    }
    

    相关文章

      网友评论

          本文标题:ios ~ UITableView 中,cell赋值方法中cel

          本文链接:https://www.haomeiwen.com/subject/vnjnjrtx.html