Auto Layout, Playgrounds, and Xcode

Today, someone asked what the easiest way was to center a view (specifically a UIImageView) inside a parent view with minimum offsets from the top and sides.

Because you’re working with image views, it’s important that you first set the content mode. For insets, it’s almost always best to go with a “fitting” aspect-scale, which preserves the entire picture even if it has to pillarbox or letterbox. (Pillarboxing adds extra spacing to each side for tall images; letterboxing adds the top and bottom for wide ones.)

// set content mode
imageView.contentMode = .scaleAspectFit

Make sure your view can squish its content by lowering its compression resistance:

[UILayoutConstraintAxis.horizontal, .vertical].forEach {
    imageView
        .setContentCompressionResistancePriority(
            UILayoutPriority(rawValue: 100), for: $0)
}

You must preserve your image’s aspect ratio. Calculate your target ratio by dividing its width by its height:

let size = imageView.image?.size ?? CGSize()
let aspectRatio = size.width / size.height

Add strong constraints that preserve the aspect, and make the view smaller than its parent using inset values you supply:

let insets = CGSize(width: 20.0, height: 32.0)

let constraints = ([
    // Preserve image aspect
    imageView.widthAnchor
        .constraint(equalTo: imageView.heightAnchor, multiplier: aspectRatio),
 
    // Make view smaller than parent
    imageView.widthAnchor
        .constraint(lessThanOrEqualTo: parentView.widthAnchor,
                    constant: -insets.width * 2),
    imageView.heightAnchor
        .constraint(lessThanOrEqualTo: parentView.heightAnchor,
                    constant: -insets.height * 2),

    // Center in parent
    imageView.centerXAnchor
        .constraint(equalTo: parentView.centerXAnchor),
    imageView.centerYAnchor
        .constraint(equalTo: parentView.centerYAnchor),
])

If you want to be super cautious, keep the aspect and two center constraints at 1000 and bring the width and height ones down to 999. You can install the constraints as you create them but I prefer to break that part out so I can tweak the priorities for each constraint group:

constraints.forEach {
    $0.priority = UILayoutPriority(rawValue: 1000)
    $0.isActive = true
}

I always mess up with the signs (positive or negative) of the constants. It helps to test these out in a playground rather than going by memory because the signs aren’t always intuitive. Even better, write routines that automates your Auto Layout tasks because if you debug once (and add proper tests), you never have to think about it again.

Mac playgrounds are inherently superior to iOS ones as they don’t run a simulator and are faster and more responsive. That is to say, you don’t have to quit and relaunch Xcode quite so often. If you are debugging iOS layouts though, and your playground hangs when starting the simulator or running your code, learn to quit, kill the core simulator service, and relaunch Xcode. It will save you a lot of time.

I have a one liner in my utilities to deal with the service:

% cat ~/bin/simfix
killall -9 -v com.apple.CoreSimulator.CoreSimulatorService

Most of the time a single quit, simfix, and launch will get things moving again with recalcitrant iOS playgrounds. Be aware that malformed format strings and other auto layout issues won’t produce especially helpful feedback, especially compared to the runtime output of compiled projects. If you know what you’re doing, you can set up a simple layout testbed in playgrounds with less overhead and time than, for example, a one view project but at a cost.

Stick to projects, and avoid playgrounds, when testing even mildly complex code-based layouts. You cannot, at this time (at least as far as I know), control which simulator will be used in the playground so it’s not great for checks on a multitude of simulator geometries. The tl;dr is that playgrounds work for general layout routines. Prefer compiled projects for specific tasks.

Comments are closed.