Forum Xamarin.iOS

TableView image from url changes while scrolling

SarathNageshSarathNagesh USMember ✭✭

This is how I load the image in to an ImageView inside a UITableViewCell..

public async void LoadImage(UIImageView imageView, int articleId)
{
    var contents = await RestCalls.GetArticleImage(Constants.__IOS__, articleId);
    if (contents != null)
        imageView.Image = UIImage.LoadFromData(NSData.FromArray(contents));
    else 
        imageView.Image = UIImage.FromFile("image-placeholder.png");
}

public override UITableViewCell GetCell(UITableView tableView, Foundation.NSIndexPath indexPath)
{
    UITableViewCell cell = tableView.DequeueReusableCell(CellIdentifier);
    if (cell == null)
    {
        cell = new UITableViewCell(UITableViewCellStyle.Default, CellIdentifier);
    }

    UIImageView imageView = (UIImageView)cell.ViewWithTag(TAG_IMAGEVIEW);
    UILabel titleLabel = (UILabel)cell.ViewWithTag(TAG_LABEL_TITLE);
    UILabel descLabel = (UILabel)cell.ViewWithTag(TAG_LABEL_DESC);
    UILabel dateLabel = (UILabel)cell.ViewWithTag(TAG_LABEL_DATE);

    Article article = articleList[indexPath.Row];
    LoadImage(imageView, Int32.Parse(article.articleId));


    .....
    return cell;
}

but the images are getting changed while scrolling. What am I doing wrong here?

any help is appreciated..

Answers

  • FinHorsleyFinHorsley USMember ✭✭

    in your cell override PrepareForReuse{} and then set your image to null. The image changes on scroll because the cells are dequeued and then reused, therefore the values in the cell are also reused. By using PrepareForReuse to set the values to null when the cell loads again, the correct values are used.

Sign In or Register to comment.