swiftswiftui

SwiftUI Image 'minWidth: .zero': What's the purpose of this setting?


I have seen this code in a video-tutorial:

Image(.paper)
    .resizable()
    .scaledToFill()
    .frame(minWidth: .zero, maxWidth: .infinity,
           minHeight: .zero, maxHeight: .infinity)

I don't understand, what's the purpose of the minWidth and minHeight-settings.

I know that zero means the default-value of an uninitialized variable, but I don't understand what it does here. I removed it and couldn't notice a difference.

Can someone explain the frame-arguments in an easy to understandable way?


Solution

  • The .frame modifier will only have an effect if the min-limit is different to the default minimum size, or if the max-limit is different to the default maximum size. However, an image with the .resizable modifier can adapt to any size, which means its minimum size is 0 and maximum size is infinity. So the frame modifier is having no effect at all in this particular case.

    More generally, the layout will normally try to give a view the space it needs for its ideal size. Setting a min size sets a limit on the smallest size that the view can reduce to. Likewise, setting a max size sets a limit on the largest size it can expand to. It can also work the other way, so the min size can tell the layout that the view cannot be smaller than the min size, or it can expand to the max size if space is available.

    For the case of an image, the ideal width and height are its natural dimensions. So if you didn't use .scaledToFill, it would adopt its natural size, if it could. Setting min and max allows the image to be squeezed into a smaller space down to the limit supplied, or expanded to fill a larger space up to the limit supplied. The aspect ratio is only respected if a scaling modifier is used (.scaledToFit or .scaledToFill), or the modifier .aspectRatio.