iOS
UIView
Swift
Auto Layout
Mobile Development

How to center a subview of UIView

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Centering one view inside another is a basic UIKit task, but the right technique depends on whether your layout should adapt to rotation, Dynamic Type, and varying device sizes. In modern UIKit code, Auto Layout is usually the correct tool because it keeps the subview centered as the parent view changes.

Center with Auto Layout

The most reliable approach is to disable autoresizing mask translation and constrain the child view’s center to the parent view’s center.

swift
1import UIKit
2
3final class DemoViewController: UIViewController {
4    override func viewDidLoad() {
5        super.viewDidLoad()
6
7        let box = UIView()
8        box.backgroundColor = .systemBlue
9        box.translatesAutoresizingMaskIntoConstraints = false
10
11        view.addSubview(box)
12
13        NSLayoutConstraint.activate([
14            box.centerXAnchor.constraint(equalTo: view.centerXAnchor),
15            box.centerYAnchor.constraint(equalTo: view.centerYAnchor),
16            box.widthAnchor.constraint(equalToConstant: 120),
17            box.heightAnchor.constraint(equalToConstant: 120)
18        ])
19    }
20}

This keeps the box centered even when the screen size changes, the device rotates, or the view controller appears in a different container.

Why Auto Layout Is Usually Better Than Frames

You can also center a subview by setting its center or frame manually.

swift
let box = UIView(frame: CGRect(x: 0, y: 0, width: 120, height: 120))
box.center = view.center
view.addSubview(box)

That works for simple static layouts, but it is fragile. If view.bounds changes later, the child no longer stays centered unless you update its position again. Manual frame layout can still be appropriate for custom drawing or very performance-sensitive code, but most app interfaces benefit from constraints.

Center Relative to Another Container View

Often you do not want to center relative to the entire screen. You want to center inside a card, banner, or other container.

swift
1let container = UIView()
2let label = UILabel()
3
4container.translatesAutoresizingMaskIntoConstraints = false
5label.translatesAutoresizingMaskIntoConstraints = false
6label.text = "Loading"
7
8view.addSubview(container)
9container.addSubview(label)
10
11NSLayoutConstraint.activate([
12    container.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
13    container.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
14    container.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40),
15    container.heightAnchor.constraint(equalToConstant: 160),
16
17    label.centerXAnchor.constraint(equalTo: container.centerXAnchor),
18    label.centerYAnchor.constraint(equalTo: container.centerYAnchor)
19])

The important rule is simple: constrain the subview to the view it should actually be centered inside.

Centering in layoutSubviews or viewDidLayoutSubviews

If you are building a custom UIView and intentionally managing frames yourself, update the child position after the parent view knows its final size.

swift
1final class CenteringView: UIView {
2    private let circle = UIView(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
3
4    override init(frame: CGRect) {
5        super.init(frame: frame)
6        circle.backgroundColor = .systemRed
7        addSubview(circle)
8    }
9
10    required init?(coder: NSCoder) {
11        fatalError("init(coder:) has not been implemented")
12    }
13
14    override func layoutSubviews() {
15        super.layoutSubviews()
16        circle.center = CGPoint(x: bounds.midX, y: bounds.midY)
17    }
18}

Using bounds.midX and bounds.midY is better than hardcoding coordinates because it follows the current size of the parent view.

Safe Areas and Visual Alignment

Sometimes a view is technically centered in the full screen but looks wrong because navigation bars, tab bars, or safe area insets shift the usable content region. If you want visual centering within the safe area, anchor to a container constrained to the safe area first.

That distinction matters most on phones with notches, embedded controllers, and split-screen layouts on iPad.

Common Pitfalls

A common mistake is forgetting to set translatesAutoresizingMaskIntoConstraints = false before adding constraints. Another is centering the subview relative to self.view when it should be centered inside another container. Developers also run into problems by setting frames in viewDidLoad, before the final layout size is known. Finally, mixing manual frames and Auto Layout on the same subview often leads to constraints fighting with later frame assignments.

Summary

  • Use Auto Layout for adaptive centering in most UIKit code.
  • Constrain the subview to the container it should visually belong to.
  • Manual frame centering is acceptable for custom layout code, but update it after sizing.
  • Use bounds, not guessed coordinates, when centering manually.
  • Watch for safe areas and autoresizing-mask conflicts when layouts behave unexpectedly.

Course illustration
Course illustration

All Rights Reserved.