SwiftUI layout Priority modifier
Amit Ranjan ?
CEO, Evangelist Apps | Creating Next-Gen Mobile Experiences | Innovating with AI & Emerging Technologies | Vision Pro & AR Innovator | Exploring the Future of Tech | Driving The Climate App | Tech Enthusiast
While working with SwiftUI we often come across situations where we want the image to maintain aspect ratio and at the same time follow the design requirement.
Let's say we have two views that take dynamic heights. One is image view whose width should be the parent width and height is determined by the aspect ratio. The other view takes the rest of the available height. Like below:
Lets code for the above requirement:
But the result for the above code is:
The reason for the above output is, by default all the views have priority 0 that causes available free space to be evenly distributed among sibling views. Image view gets half of the parent height, and to maintain aspect ratio the width of the image is reduced leaving empty space on left and right. But we want image’s width to be same as parent width.
In order to maintain screen width as well as aspect ratio, Image view needs to be laid out first and the other view later in the available height. This can be achieved by increasing the layout priority of image view through layoutPriority modifier like below:
Raising a view’s layout priority encourages the higher priority view to shrink later when the group is shrunk and stretch sooner when the group is stretched.
Please share your thoughts and suggestions on this article.