Skip to content

Instantly share code, notes, and snippets.

@dnedrow
Created February 13, 2024 20:14
Show Gist options
  • Select an option

  • Save dnedrow/c6f8139a04962e6a508d0ff8409e8463 to your computer and use it in GitHub Desktop.

Select an option

Save dnedrow/c6f8139a04962e6a508d0ff8409e8463 to your computer and use it in GitHub Desktop.
Provides View that are dynamically sized based on a base size
import SwiftUI
struct DynamicSize {
static private let baseViewWidth: CGFloat = 414.0
static private let baseViewHeight: CGFloat = 896.0
static func getHeight(_ height: CGFloat) -> CGFloat {
return (height / baseViewHeight) * UIScreen.main.bounds.height
}
static func getWidth(_ width: CGFloat) -> CGFloat {
return (width / baseViewWidth) * UIScreen.main.bounds.width
}
static func getOffsetX(_ x: CGFloat) -> CGFloat {
return (x / baseViewWidth) * UIScreen.main.bounds.width
}
static func getOffsetY(_ y: CGFloat) -> CGFloat {
return (y / baseViewHeight) * UIScreen.main.bounds.height
}
}
extension View {
func frame(dynamicWidth: CGFloat? = nil, dynamicHeight: CGFloat? = nil, alignment: Alignment = .center) -> some View {
frame(
width: DynamicSize.getWidth(dynamicWidth ?? 0),
height: DynamicSize.getHeight(dynamicHeight ?? 0),
alignment: alignment)
}
func offset(dynamicX: CGFloat = 0, dynamicY: CGFloat = 0) -> some View {
offset(x: DynamicSize.getOffsetX(dynamicX), y: DynamicSize.getOffsetY(dynamicY))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment