Swift
iOS development
device rotation
programming tutorial
mobile app development

iOS How to run a function after Device has Rotated Swift

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

On iOS, the safest way to run code after a rotation is usually through the view controller transition lifecycle, not by guessing based on raw device-orientation notifications. If your goal is to update layout, restart an animation, or recalculate geometry after the interface changes size, use the APIs that are tied to the actual rotation transition.

Prefer viewWillTransition(to:with:)

For most UIKit apps, viewWillTransition(to:with:) is the right place to respond to a rotation. It is called when the interface is about to change size, and the transition coordinator lets you run code during or after the rotation animation.

swift
1import UIKit
2
3final class PhotoViewController: UIViewController {
4    override func viewWillTransition(
5        to size: CGSize,
6        with coordinator: UIViewControllerTransitionCoordinator
7    ) {
8        super.viewWillTransition(to: size, with: coordinator)
9
10        coordinator.animate(alongsideTransition: { _ in
11            self.updateLayout(for: size)
12        }, completion: { _ in
13            self.runAfterRotation()
14        })
15    }
16
17    private func updateLayout(for size: CGSize) {
18        print("updating layout for", size)
19    }
20
21    private func runAfterRotation() {
22        print("rotation finished")
23    }
24}

If you truly need the function after the rotation completes, put it in the coordinator's completion block. That timing is better than trying to guess whether the screen has already settled.

Why Orientation Notifications Are Not the Best Default

You can observe UIDevice.orientationDidChangeNotification, but that notification tracks the device's physical orientation, not necessarily the interface rotation you care about.

For example, the device can report .faceUp, .faceDown, or an orientation change that does not lead to a visible interface rotation. That makes notification-based code noisy for layout work.

A notification approach is still possible:

swift
1import UIKit
2
3final class RotationObserverViewController: UIViewController {
4    override func viewDidLoad() {
5        super.viewDidLoad()
6
7        NotificationCenter.default.addObserver(
8            self,
9            selector: #selector(deviceDidRotate),
10            name: UIDevice.orientationDidChangeNotification,
11            object: nil
12        )
13    }
14
15    @objc private func deviceDidRotate() {
16        let orientation = UIDevice.current.orientation
17        guard orientation.isPortrait || orientation.isLandscape else {
18            return
19        }
20
21        print("device orientation changed to", orientation.rawValue)
22    }
23
24    deinit {
25        NotificationCenter.default.removeObserver(self)
26    }
27}

That is acceptable when you genuinely care about raw device orientation, but it is usually the wrong tool for post-rotation UI work.

Running Code After Auto Layout Has Settled

Sometimes what you actually need is not "after rotation" but "after views have their final frames." In that case, viewDidLayoutSubviews() can be a better place to act, especially if your logic depends on final view sizes.

swift
1import UIKit
2
3final class DashboardViewController: UIViewController {
4    private var previousSize: CGSize = .zero
5
6    override func viewDidLayoutSubviews() {
7        super.viewDidLayoutSubviews()
8
9        guard view.bounds.size != previousSize else {
10            return
11        }
12
13        previousSize = view.bounds.size
14        updateChartLayout()
15    }
16
17    private func updateChartLayout() {
18        print("layout is now based on", view.bounds.size)
19    }
20}

This pattern is useful when rotation changes constraints and you need the final layout before doing expensive recalculation.

Trait Changes and Size Classes

On modern iOS, rotation is not the only reason the interface may change. Split view, slide over, and iPad multitasking can also change available size. That is why size-based APIs are often better than raw orientation checks.

If the behavior depends on compact versus regular width, size classes may matter more than portrait versus landscape. Thinking in terms of available space makes the code more robust across devices.

Common Pitfalls

One common mistake is relying on UIDevice.current.orientation for layout decisions. The physical device orientation is not always the same as the current interface state.

Another problem is doing work too early. If you read frames before the rotation transition or Auto Layout pass finishes, you may calculate with stale sizes.

Developers also sometimes forget that not every size change is a traditional rotation. On iPad, the app can resize without the device turning at all, so code that only thinks in terms of portrait and landscape becomes brittle.

Finally, if you use notifications, remember to remove observers when appropriate. Otherwise the controller can keep receiving rotation events after it should be gone.

Summary

  • Use viewWillTransition(to:with:) for most rotation-related UIKit work.
  • Put post-rotation logic in the transition coordinator completion block.
  • Use viewDidLayoutSubviews() when you need final view sizes after layout.
  • Avoid using raw orientation notifications for layout unless you truly need device orientation.
  • Prefer size-based thinking over portrait-versus-landscape assumptions.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.