首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >是否在UItableView单元格中自动添加图像?

是否在UItableView单元格中自动添加图像?
EN

Stack Overflow用户
提问于 2015-10-24 13:11:51
回答 8查看 221关注 0票数 7

Helo all

我在这里遇到了一个非常奇怪的情况,我有一个表格视图,其中包含自定义单元格。所以我设计了自己的自定义cell.In自定义单元格,我也在显示图像,text.The表的数据来自于server.If,json中的任何图像,然后图像将被显示,否则只有文本是displayed.So单元格将是动态的。我已经使用bezier path将文本包裹在image.No周围,如果图像在那里,那么文本将是wrapped.When。我用图像从服务器添加新的帖子&我刷新表格,然后它会自动显示其他帖子的图像,因为well.It将显示相同的图像,最后是相同的图像。我不知道为什么新的单元格在它的单元格中添加图像,即使代码运行良好,我已经用breakpoints.Please调试过了,告诉它可能是什么问题。

下面是cellForRowAtIndexPath的代码

代码语言:javascript
运行
复制
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //define variables here
    static NSString *CellIdentifier = @"homeCell";
    HomeCell *cell = [tableView
                      dequeueReusableCellWithIdentifier:CellIdentifier
                      forIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    if([arr_post count]>0)
    {
        NSMutableAttributedString *mutableAttributeStr;
        NSAttributedString *attributeStr;

        [cell layoutIfNeeded];
        //get the post data
        Post *user_post=[arr_post objectAtIndex:indexPath.row];

        //set the button tags
        cell.btn_like.tag=indexPath.row;
        cell.btn_comment.tag=indexPath.row;
        cell.btn_fav.tag=indexPath.row;
        cell.btn_con.tag=indexPath.row;
        cell.btn_book.tag=indexPath.row;

        //add info to buttons
        cell.btn_like.selected=user_post.isPostLiked;
        cell.btn_comment.selected=user_post.isPostCommented;
        cell.btn_fav.selected=user_post.isPostFavourite;
        cell.btn_con.selected=user_post.isPostCondolence;
        cell.btn_book.selected=user_post.isPostBookmarked;

        //add user info
        cell.label_name.text=user_post.username;
        cell.img_profile.layer.cornerRadius = 25;
        cell.img_profile.clipsToBounds = YES;
        [cell.img_profile setImageWithURL:[NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:user_post.user_profileImage]]placeholderImage:[UIImage imageNamed:@"post_placeholder.png"]];
        //add location
        if([user_post.location isEqualToString:@"Not Available"])
        {
            [cell.img_icon_location setHidden:true];
            [cell.label_location setHidden:true];
        }
        else
        {
            [cell.img_icon_location setHidden:false];
            [cell.label_location setHidden:false];
            cell.label_location.text=user_post.location;
        }
        //ad post info
        cell.tv_post.text=user_post.post_description;
        cell.tv_post.font = [UIFont fontWithName:user_post.font_family size:[user_post.font_size floatValue]];
        [cell.tv_post setTextColor:[self colorFromHexString:user_post.font_color]];

        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *date = [formatter dateFromString:user_post.modification_date];
        NSLog(@"user post image is %@",user_post.post_image);

        if([user_post.post_image isEqualToString:@"none"] && [user_post.post_video isEqualToString:@"none"])
        {

            NSLog(@"NOT INSIDE THE CONDITION");

        }
        else
        {
            NSLog(@"INSIDE BEIZER PATH CONDITION");
            UIBezierPath * imgRect = [UIBezierPath bezierPathWithRect:CGRectMake(0, 10, 100, 100)];
            cell.tv_post.textContainer.exclusionPaths = @[imgRect];
            UIImageView *tv_image =[[UIImageView alloc]initWithFrame:CGRectMake(0, 10, 100, 100)];

            if(![user_post.post_image isEqualToString:@"none"])
            {
                [tv_image setImageWithURL:[NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:user_post.post_image]]placeholderImage:[UIImage imageNamed:@"post_placeholder.png"]];

            }
            if(![user_post.post_video isEqualToString:@"none"])
            {
                [tv_image setImageWithURL:[NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:user_post.post_video_thumbnail]]placeholderImage:[UIImage imageNamed:@"post_placeholder.png"]];

            }

            [cell.tv_post addSubview:tv_image];
        }
        //make textview height dynamic
        cell.tv_post.scrollEnabled=NO;
        if([user_post.post_image isEqualToString:@"none"] && [user_post.post_video isEqualToString:@"none"])
        {
            CGFloat fixedWidth = cell.tv_post.frame.size.width;
            CGSize newSize = [cell.tv_post sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
            CGRect newFrame = cell.tv_post.frame;
            newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
            cell.tv_post.frame = newFrame;
            cell.tv_height.constant=cell.tv_post.frame.size.height;
            [cell.view_tvContainer layoutIfNeeded];
        }
               //set the border of uiview
        cell.view_tvContainer.layer.borderColor = [UIColor blackColor].CGColor;
        cell.view_tvContainer.layer.borderWidth = 2.0f;

        //set the like count
        NSString *first_like_user=recent_like_name=user_post.recent_like_name;
        NSLog(@"FIRST LIEK USER IS %@",first_like_user);
        NSString *str_recent_like_name;
        int count=(int)[first_like_user length];
        int like_count=[user_post.like_count intValue];
        if(like_count>0)
        {
            cell.label_like_count.lineBreakMode=NSLineBreakByWordWrapping;
            [cell.label_like_count sizeToFit];
            [cell.label_like_count setHidden:false];
            NSString *str_like_count=[NSString stringWithFormat:@"%lu",(unsigned long)like_count-1];
            if(like_count==1)
            {
                if([myUsername isEqualToString:first_like_user])
                {
                    first_like_user=@"You like this post ";
                    count=3;
                }
                else
                {
                    first_like_user=[first_like_user stringByAppendingString:@" like this post"];
                }
            }
            else if(like_count==2)
            {
                if([first_like_user isEqualToString:myUsername])
                {
                    first_like_user=@"You";
                }
                Post *temp_user_post=[copy_arr_user_post objectAtIndex:indexPath.row];
                first_like_user=[first_like_user stringByAppendingString:@" and "];
                if(temp_user_post.recent_like_name==nil)
                {
                    temp_user_post.recent_like_name=@"";
                }
                str_recent_like_name=[temp_user_post.recent_like_name_two stringByAppendingString:@" like this post"];
                first_like_user=[first_like_user stringByAppendingString:str_recent_like_name];
            }
            else
            {
                if(like_count>1000)
                {
                    like_count=like_count/1000;
                    str_like_count=[NSString stringWithFormat:@"%lu",(unsigned long)like_count];
                    str_like_count=[str_like_count stringByAppendingString:@"k"];
                    first_like_user=[first_like_user stringByAppendingString:@" and "];
                    str_like_count=[str_like_count stringByAppendingString:@" others like this post"];
                    first_like_user=[first_like_user stringByAppendingString:str_like_count];
                }
                else
                {
                    if([first_like_user isEqualToString:myUsername])
                    {
                        first_like_user=@"You";
                    }
                    first_like_user=[first_like_user stringByAppendingString:@" and "];
                    str_like_count=[str_like_count stringByAppendingString:@" others like this post"];
                    first_like_user=[first_like_user stringByAppendingString:str_like_count];
                }
            }
            mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:first_like_user];
            attributeStr = [[NSAttributedString alloc]initWithString:@"\n" attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]}];

            [mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica-Bold" size:14.0]  range:NSMakeRange(0, count)];
            [mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:@"#48a0dd"] range:NSMakeRange(0, count)];

            [mutableAttributeStr appendAttributedString:attributeStr];

            [cell.label_like_count setAttributedText:mutableAttributeStr];
        }
        else
        {
            [cell.label_like_count setHidden:true];


        }
        // show dynamic comment
        NSMutableArray *user_comments=user_post.comments;
        float comment_count=[user_post.comment_count intValue];
         NSLog(@"ID IS %@",user_post.id);
        if(comment_count>0)
        {
            //make label multiline
            cell.first_comment.lineBreakMode=NSLineBreakByWordWrapping;
            [cell.first_comment sizeToFit];
            cell.second_cmment.lineBreakMode=NSLineBreakByWordWrapping;
            [cell.second_cmment sizeToFit];
            cell.third_comment.lineBreakMode=NSLineBreakByWordWrapping;
            [cell.third_comment sizeToFit];

            if(comment_count==1)
            {
                [cell.first_comment setHidden:false];
                [cell.second_cmment setHidden:true];
                [cell.third_comment setHidden:true];

            }
            else if(comment_count==2)
            {
                [cell.first_comment setHidden:false];
                [cell.second_cmment setHidden:false];
                [cell.third_comment setHidden:true];

            }
            else
            {
                [cell.first_comment setHidden:false];
                [cell.second_cmment setHidden:false];
                [cell.third_comment setHidden:false];
                [cell.btn_more_comments setHidden:false];

            }
            for(l=0;l<[user_comments count];l++)
            {
                Comment *comment=[user_comments objectAtIndex:l];
                NSString *comment_string=[comment.user_name stringByAppendingString:@" "];
                comment_string=[comment_string stringByAppendingString:comment.comment];
                int count=(int)[comment.user_name length];
                NSMutableAttributedString* mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string];
                NSAttributedString *attributeStr = [[NSAttributedString alloc]initWithString:@"\n" attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]}];

                [mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica-Bold" size:14.0]  range:NSMakeRange(0, count)];
                [mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:@"#48a0dd"] range:NSMakeRange(0, count)];

                [mutableAttributeStr appendAttributedString:attributeStr];
                // end of the repetitive pattern
                if (l == 0)
                {
                    [cell.first_comment setAttributedText:mutableAttributeStr];
                }
                else if (l == 1)
                {
                    [cell.second_cmment setAttributedText:mutableAttributeStr];
                }
                else if (l == 2)
                {
                    [cell.third_comment setAttributedText:mutableAttributeStr];
                }
            }
        }
        else
        {
            [cell.first_comment setHidden:true];
            [cell.second_cmment setHidden:true];
            [cell.third_comment setHidden:true];
            [cell.btn_more_comments removeFromSuperview];
        }
        cell.label_time.text=[BaseController timeAgoStringFromDate:date];
        [arr_indexpath addObject:indexPath];

    }

    return cell;
}
EN

回答 8

Stack Overflow用户

发布于 2015-10-24 16:41:59

请记住,这些单元是重复使用的。假设您的表数据源中有10000行,那么表视图不会创建那么多行。它只会创建足够的行显示在屏幕上,以及其他几个要预加载的行。

每次滚动表格时,tableview将使用那些不可见的单元格来加载刚刚变为可见的新单元格,从而产生无限行数的错觉。这就是为什么这些新单元格具有旧数据。因此,基本上,如果没有可用的镜像,您必须在cellForRowAtIndexpath:中将UIImageView的镜像设置为nil

代码语言:javascript
运行
复制
if([user_post.post_image isEqualToString:@"none"] && [user_post.post_video isEqualToString:@"none"])
        {

            NSLog(@"NOT INSIDE THE CONDITION");

        }

在上面的代码中,您只需打印出一个日志,而您还必须将UIImageView's图像设置为nil

所以这是我的建议:

代码语言:javascript
运行
复制
//if([user_post.post_image isEqualToString:@"none"] && [user_post.post_video isEqualToString:@"none"])
//{

//   NSLog(@"NOT INSIDE THE CONDITION");

//}
//else
{
    NSLog(@"INSIDE BEIZER PATH CONDITION");
    UIBezierPath * imgRect = [UIBezierPath bezierPathWithRect:CGRectMake(0, 10, 100, 100)];
    cell.tv_post.textContainer.exclusionPaths = @[imgRect];
    UIImageView *tv_image =[[UIImageView alloc]initWithFrame:CGRectMake(0, 10, 100, 100)];

    if(![user_post.post_image isEqualToString:@"none"])
    {
        [tv_image setImageWithURL:[NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:user_post.post_image]]placeholderImage:[UIImage imageNamed:@"post_placeholder.png"]];

    }
    else{
        [tv_image setImage:nil]; //Prevent the old data to be shown
    }

    if(![user_post.post_video isEqualToString:@"none"])
    {
        [tv_image setImageWithURL:[NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:user_post.post_video_thumbnail]]placeholderImage:[UIImage imageNamed:@"post_placeholder.png"]];

    }
    else{
        [tv_image setImage:nil];//Prevent the old data to be shown
    }

    [cell.tv_post addSubview:tv_image];
}

也许这段代码不符合您对数据显示方式的要求,但希望它能帮助您理解!

票数 1
EN

Stack Overflow用户

发布于 2015-10-24 16:18:53

当需要显示表视图单元格时,您可以创建一个新的单元格,也可以重用先前创建但在屏幕上不再可见的单元格。因为您已经创建了一个UIImageView并将其添加到一个单元格中,所以当您重用它时,图像仍然在那里。

为了阻止这种情况的发生,你需要保留一个对图像视图的引用,这样下次你就可以删除它了。由于您是动态添加它们的,并且没有IBOutlet,因此最快的选择是为图像分配一个tag

代码语言:javascript
运行
复制
UIImageView *tv_image =[[UIImageView alloc]initWithFrame:CGRectMake(0, 10, 100, 100)];
tv_image.tag = 21; // arbitrary number but must be unique to the image

通过标记图像,下一次您可以访问它:

代码语言:javascript
运行
复制
UIImageView *tv_image = (UIImageView*)[cell viewWithTag:21];
if (tv_image != nil) {
    tv_image.image = nil; // remove the image (or remove the image view from the cell etc)
}

只需确保相应地重构代码,以便在从标记中找到图像时,不需要重新创建它,等等

票数 0
EN

Stack Overflow用户

发布于 2015-10-27 13:12:11

您的img_profile正在重复,因为您正在重用该单元格。

替换下面的代码行

代码语言:javascript
运行
复制
[cell.img_profile setImageWithURL:[NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:user_post.user_profileImage]]placeholderImage:[UIImage imageNamed:@"post_placeholder.png"]];

使用以下代码:

代码语言:javascript
运行
复制
    if (user_post.user_profileImage.length == 0) {
        cell.img_profile.hidden = true;
    }else{
        [cell.img_profile setImageWithURL:[NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:user_post.user_profileImage]]placeholderImage:[UIImage imageNamed:@"post_placeholder.png"]];
    }

说明:-检查您的json是否包含用户配置文件图像,然后设置图像,否则隐藏配置文件图像视图。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33314766

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档