Since Xcode 8 and iOS10, views are not sized properly on viewDidLayoutSubviews
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Since the release of Xcode 8 and iOS 10, many developers have noticed a peculiar issue where views are not sized correctly within the viewDidLayoutSubviews
method. This has stirred some frustration within the iOS development community, as accurate sizing is crucial for creating responsive and visually appealing applications. In this article, we'll explore the technical underpinnings of this issue, provide examples where relevant, and discuss possible solutions.
Understanding viewDidLayoutSubviews
In the UIKit framework, viewDidLayoutSubviews
is a crucial method of the UIViewController
lifecycle. This method is called when the view's bounds change and its subviews are laid out. Developers often override this method to make layouts respond dynamically to changes in view size or orientation.
Changes in iOS 10 and Xcode 8
With the introduction of Xcode 8 and iOS 10, Apple made significant improvements and optimizations to the layout processing system. While these changes were designed to enhance performance and flexibility, they also introduced some challenges, particularly for views' frame calculations within viewDidLayoutSubviews
.
The Issue
The core issue is that, in some cases, the frames of the views are not set to their expected values when viewDidLayoutSubviews
is called. This usually happens when using Auto Layout constraints. Views may not reflect changes in layout constraints or may not account for safe area insets properly.
Example:
Consider the scenario where a button needs to be centered within its parent view using Auto Layout constraints:
Related reading
- single function to dismiss all open view controllers
- single function to dismiss all open view controllers
- Single TextView with multiple colored text
- Singletons vs. Application Context in Android?
- Singletons vs. Application Context in Android?
- Sizing a Container View with a controller of dynamic size inside a scrollview
- Slow app launch time after updating to iOS 14 and Xcode 12
- Snap to center of a cell when scrolling UICollectionView horizontally
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseTrack 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.