Ios – How to get the iPhone’s screen width in SwiftUI

iosiphoneswiftswiftui

I want to resize an Image frame to be a square that takes the same width of the iPhone's screen and consequently the same value (screen width) for height.

The following code don't work cause it gives the image the same height of the view.

var body: some View {
        Image("someImage")
            .resizable()
            .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
            .clipped()
    }

Best Answer

You can create a UIScreen extension for the same. Like:

extension UIScreen{
   static let screenWidth = UIScreen.main.bounds.size.width
   static let screenHeight = UIScreen.main.bounds.size.height
   static let screenSize = UIScreen.main.bounds.size
}

Usage:

UIScreen.screenWidth
Related Topic