Search code examples
iosobjective-cuitableviewnslayoutconstraintsdwebimage

Collapse UIImageview in UITableview cell, when it doesn't return an image


Summary of the problem

I have a UITableView in which I want to Collapse it's UIImageView cell part, whenever it doesn't return an image, as seen below

first image of tableview cell (the expected result)

The correct form second image of tableview cell (the no image result)

No image form

Background including what I've already tried

Below is the piece of code that I have been working on. Also notice that I'm using SDWebImage to get and set the image in the app (any method in tableview delegates, SDWebImage protocols etc that I'm missing just point me),

The comment out part is what I have done, i.e. used constraints to try the collapse of UIimageView not it messes up the whole tableView upon scrolling

Code

Here is piece of code I'm working on,

[cell.i_imageView sd_setImageWithURL:[NSURL URLWithString: item.PostimageUrl] placeholderImage:[UIImage imageNamed:@"no-image"] options:SDWebImageRefreshCached completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {

        if(!image)
        {
                    //cell.i_imageView.hidden = YES;

            NSLog(@"why no image des:%@",error);
            NSLog(@"why no image url:%@",imageURL);
        }

//            cell.imageHolderAspectConstraint.active = TRUE;
//            cell.imageHolderZeroImageConstraint.active = FALSE;
//        }
//        else
//        {
//            cell.imageHolderAspectConstraint.active = FALSE;
//            cell.imageHolderZeroImageConstraint.active = TRUE ;
//
//            [cell layoutIfNeeded];
//            [cell setNeedsLayout];
//        }

        [cell.i_imageView sd_removeActivityIndicator];

    }];

Any help in this matter is highly appreciated, cheers.

Edit

Here is the image of storyboard section, where do I need to embed stackview

enter image description here

enter image description here


Solution

  • Add your ImageView in StackView. Now hide your ImageView when image is not available.

    Note : UIStackView automatically handle height of cell.

    Edit:

    As of now your UI is something like this.

    enter image description here

    Now select your image holding view and click on embedded in and select UIStackView.

    enter image description here

    Now assign the same constraints that you have given to holding view to stackView.

    Now your hierarchy is like below

    enter image description here

    Finally you need to do below code in CellForRow:

    cell.vImageHoldingView.hidden = !image;