Reputation: 81
How is idealwidth different from normal width in swiftUI frames?
Upvotes: 7
Views: 4461
Reputation: 1099
I'm not 100% on this, but it looks like idealWidth
and idealHeight
are used when the parent view proposes a nil
width or height to its children in the layout process. In that case the children will use their ideal size.
One scenario where this is the case is when a view is in a ScrollView
. Along the scrolling axes, the child views will use their ideal width/height.
I found an explanation here: https://www.swiftuifieldguide.com/layout/scrollview/
Upvotes: 1
Reputation: 781
Width and height are fixed values that define the dimensions of a frame. If you wrote something like this...
Rectangle()
.foregroundColor(.blue)
.frame(width: 200, height: 200)
...you would have a 200x200 blue square, regardless of whether or not it fits in the parent view.
However, the ideal size isn't fixed. Writing something like this...
Rectangle()
.foregroundColor(.blue)
.frame(idealWidth: 200, idealHeight: 200)
...would completely fill an empty view. That's because the ideal size is more of a gentle proposal that is outweighed in favor of the size proposed by the parent. For many predefined Views the ideal dimensions define how much space the View needs to be understood. For Text()
the ideal width is the length of the string and the ideal height is the line's height.
Looking back at our ideal sized rectangle, applying .fixedSize()
like so...
Rectangle()
.foregroundColor(.blue)
.frame(idealWidth: 200, idealHeight: 200)
.fixedSize()
...would force the ideal size and create a 200x200 blue square. If you added that modifier to Text()
you'd see it take on its ideal size as well, which in many cases would be a string so wide that it runs beyond its parent frame.
You can go further with the .fixedSize()
modifier by defining which axises the view is defined on.
Rectangle()
.foregroundColor(.blue)
.frame(idealWidth: 200, idealHeight: 200)
.fixedSize(horizontal: true, vertical: false)
In the above example, our Rectangle is fixed to its ideal width but can grow vertically to fill its parent. This can be useful for something like a custom button, where you might sometimes want to confine its height but allow it to stretch to fill its parent view.
You can learn a lot more from this article as well as this one. Apple also explores the ideal size a little in their discussion of the .fixedSize()
modifier here.
Upvotes: 12