Fix: UITableViewCell imageView Size Varies with Image Dimensions in UIKit

Fix: UITableViewCell imageView Size Varies with Image Dimensions in UIKit

Written by

in

Quick answer: The default UITableViewCell.imageView resizes to fit each image’s natural dimensions. To enforce a fixed size, either override layoutSubviews in a custom cell subclass and set imageView.frame, or resize the image to a fixed canvas before assigning it. Both approaches keep text alignment consistent and center smaller images.

Why this happens

UITableViewCell‘s built-in imageView property is a UIImageView that automatically sizes itself to the assigned image’s intrinsic content size. When you provide images of varying dimensions — 40×50, 50×32, 20×37 — the image view’s width changes per row. This shifts the textLabel and detailTextLabel horizontally, creating a ragged left edge. Additionally, the default contentMode is .scaleToFill, so smaller images stretch; setting .center alone doesn’t help because the view’s bounds still match the image’s size.

The root cause is that imageView has no intrinsic size constraint from the cell’s layout system. The cell lays out its subviews in layoutSubviews based on the image view’s current frame, which UIKit updates after you set the image.

How to fix it

1. Override layoutSubviews in a Custom Cell Subclass (Recommended)

Subclass UITableViewCell and force the image view to a constant frame after the superclass layout pass. This is the cleanest approach because it keeps sizing logic inside the cell and works with any image source.

Objective‑C

// FixedSizeImageCell.h
#import <UIKit/UIKit.h>

@interface FixedSizeImageCell : UITableViewCell
@end

// FixedSizeImageCell.m
#import "FixedSizeImageCell.h"

@implementation FixedSizeImageCell

- (void)layoutSubviews {
    [super layoutSubviews];
    // Adjust the constant (e.g., 40×40) to your design spec
    self.imageView.frame = CGRectMake(0, 0, 40, 40);
    self.imageView.contentMode = UIViewContentModeCenter;
}

@end

Swift

import UIKit

final class FixedSizeImageCell: UITableViewCell {
    override func layoutSubviews() {
        super.layoutSubviews()
        imageView?.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        imageView?.contentMode = .center
    }
}

Register the class (or use a storyboard prototype cell with this class) and dequeue it normally:

tableView.register(FixedSizeImageCell.self, forCellReuseIdentifier: "Cell")

Why this works: layoutSubviews runs after the cell’s internal auto-layout pass. Overriding the frame here wins over the size UIKit computed from the image.

2. Resize the Image Before Assignment (No Subclass Needed)

If you cannot or prefer not to subclass, draw each image into a fixed‑size graphics context so the resulting UIImage already has the target dimensions. The cell’s imageView will then adopt that size naturally.

Swift (iOS 10+ / UIGraphicsImageRenderer)

func resizedImage(_ image: UIImage, to size: CGSize) -> UIImage {
    let renderer = UIGraphicsImageRenderer(size: size)
    return renderer.image { _ in
        image.draw(in: CGRect(origin: .zero, size: size))
    }
}

// In cellForRowAt:
let targetSize = CGSize(width: 40, height: 40)
cell.imageView?.image = resizedImage(originalImage, to: targetSize)
cell.imageView?.contentMode = .center

Objective‑C (Legacy UIGraphicsBeginImageContextWithOptions)

- (UIImage *)imageByScalingToSize:(CGSize)targetSize {
    UIGraphicsBeginImageContextWithOptions(targetSize, NO, [UIScreen mainScreen].scale);
    [self drawInRect:CGRectMake(0, 0, targetSize.width, targetSize.height)];
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result;
}

// Usage:
cell.imageView.image = [originalImage imageByScalingToSize:CGSizeMake(40, 40)];
cell.imageView.contentMode = UIViewContentModeCenter;

Note: The modern UIGraphicsImageRenderer (Swift) is preferred over the C‑based context API; it handles wide color and is thread‑safe.

3. Use Auto Layout Constraints (Modern Approach)

If you build cells programmatically or in a .xib, add explicit width/height constraints to imageView. This avoids frame manipulation and works with dynamic type.

// Inside a custom cell's init(style:reuseIdentifier:)
imageView?.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
    imageView!.widthAnchor.constraint(equalToConstant: 40),
    imageView!.heightAnchor.constraint(equalToConstant: 40)
])
imageView?.contentMode = .center

The cell’s layout engine will honor these constraints during its own layoutSubviews.

How to prevent it

  • Decide on a fixed thumbnail size early (e.g., 40×40 pt) and enforce it at the data layer — either by resizing on download or by using asset catalogs with preset dimensions.
  • Prefer a custom cell subclass over ad‑hoc frame changes in cellForRowAt; it centralizes layout logic and survives cell reuse.
  • Set contentMode = .center whenever you fix the frame so smaller images sit in the middle instead of top‑left.
  • Test with varying image aspect ratios (portrait, landscape, square) to verify alignment.

FAQ

Does this affect accessory views or trailing swipe actions?

No. The imageView sits on the leading side of the cell’s content view. Constraining its width does not interfere with accessoryView, accessoryType, or trailing swipe configurations.

Can I use this with UITableViewCell styles like .subtitle?

Yes. The built‑in styles (default, subtitle, value1, value2) all use the same imageView property. The fixes above work identically.

What if I need different image sizes per section?

Adjust the constant in layoutSubviews or the constraint constant based on indexPath.section. For example:

override func layoutSubviews() {
    super.layoutSubviews()
    let size: CGFloat = (indexPath?.section == 0) ? 60 : 40
    imageView?.frame = CGRect(x: 0, y: 0, width: size, height: size)
}

Pass the indexPath to the cell via a custom property when dequeuing.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.