Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the iPhone's screen width in SwiftUI?

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()
    }
like image 960
Rubens Neto Avatar asked Aug 30 '19 12:08

Rubens Neto


People also ask

How do I change the frame size in SwiftUI?

By default SwiftUI's views take up only as much space as they need, but if you want that to change you can use a frame() modifier to tell SwiftUI what kind of size range you want to have. Note: if you want a view to go under the safe area, make sure you add the ignoresSafeArea() modifier.


3 Answers

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
like image 74
bestiosdeveloper Avatar answered Oct 18 '22 22:10

bestiosdeveloper


Try using Geometry Reader

let placeholder = UIImage(systemName: "photo")! // SF Symbols

struct ContentView: View {
    var body: some View {
        GeometryReader { geometry in
            Image(uiImage: placeholder) 
            .resizable()
            .frame(width: geometry.size.width, height: geometry.size.height, alignment: .center)
            // .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
            .clipped()
        }
    }
}

enter image description here

like image 36
DoesData Avatar answered Oct 18 '22 22:10

DoesData


You can use UIScreen.main.bounds .width or .height

.frame(
   width:UIScreen.main.bounds.width,
   height:UIScreen.main.bounds.height
)
like image 19
Mehmet Ali Vatanlar Avatar answered Oct 18 '22 21:10

Mehmet Ali Vatanlar