rigdonmr
rigdonmr

Reputation: 2702

UIImageView cover entire UITableViewCell using aspect fill

In the interface builder, I'm trying to create a prototype cell with an image that covers the entire cell but it is not running how it is expected.

As you can see in the following screenshot of my interface builder, I have an image view covering the entire cell, and is constrained to each edge of the cell:

enter image description here

And in fact this is how I expect it to look on the simulator, but instead I get this:

enter image description here

Where as you can see, it is not anchored all the way to the sides, and it may be hard to see, but the image actually extends past the bottom of the cell (if you look hard enough you can see the separator striking through the bottom portion of the image.

This is really buggy and I really have no idea what's happening.

Upvotes: 5

Views: 2597

Answers (4)

Irfan
Irfan

Reputation: 5130

This is because you are setting constraint to margins.

When adding constraints to uiimageview. Uncheck constraint to margin.

enter image description here

Upvotes: 0

Oleksii Nezhyborets
Oleksii Nezhyborets

Reputation: 931

  1. Seems that your image constraints are relative to cells contentView margins. You can disable it, see screenshot. Be sure that constant is 0

enter image description here

  1. You need to do Clip Subviews (clipsToBounds) on cells contentView or imageView if you don't want aspect filled image to go beyond bounds. Otherwise you should use Aspect Fit, or Scale To Fill, or do the math manually

Upvotes: 0

Salim Braksa
Salim Braksa

Reputation: 130

I think you accidentally disabled cell's Clip Subviews in code or in Storyboard, by default It should be enabled.

enter image description here

If it's not the cell, check it's Content View.

enter image description here

By the way, by disabling Clip Subviews for both Cell and it's Content view, I managed to reproduce your bug.

Upvotes: 1

Pranav Wadhwa
Pranav Wadhwa

Reputation: 7736

Perhaps adding aUIImageView inside of your cell in code.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    //configure cell
    let imageView = UIImageView(frame: self.cell.frame)
    imageView.image = YOUR_IMAGE
    imageView.center = cell.center
    imageView.frame.size = cell.frame.size
    imageView.contentMode = .ScaleAspectFill
    cell.addSubview(imageView)
}

Hope this helps.

Upvotes: 1

Related Questions