'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()
}
Solution 1:[1]
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
Solution 2:[2]
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()
}
}
}
Solution 3:[3]
You can use UIScreen.main.bounds .width or .height
.frame(
width:UIScreen.main.bounds.width,
height:UIScreen.main.bounds.height
)
Solution 4:[4]
The simplest way would be to make the image resizable and set the aspect ratio to 1.0:
var body: some View {
Image("someImage")
.resizable()
.aspectRatio(1.0, contentMode: .fit)
}
Solution 5:[5]
I've come up with a solution using Environment Keys, by creating the following:
private struct MainWindowSizeKey: EnvironmentKey {
static let defaultValue: CGSize = .zero
}
extension EnvironmentValues {
var mainWindowSize: CGSize {
get { self[MainWindowSizeKey.self] }
set { self[MainWindowSizeKey.self] = newValue }
}
}
Then by reading the size from where the window is created:
var body: some Scene {
WindowGroup {
GeometryReader { proxy in
ContentView()
.environment(\.mainWindowSize, proxy.size)
}
}
}
Finally I can directly get the window size in any SwiftUI view, and it changes dynamically (on device rotation or window resizing on macOS):
@Environment(\.mainWindowSize) var mainWindowSize
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | bestiosdeveloper |
Solution 2 | |
Solution 3 | Mehmet Ali Vatanlar |
Solution 4 | Gene Z. Ragan |
Solution 5 | Thibault Farnier |