Created
July 30, 2022 04:51
-
-
Save HarshilShah/75fc82b1d56b4eeb01fed20dae908b1e to your computer and use it in GitHub Desktop.
A SwiftUI extension that scales a frame using a specified dynamic type style
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct ScalingFrameModifier: ViewModifier { | |
@ScaledMetric var width: CGFloat | |
@ScaledMetric var height: CGFloat | |
var hasWidthSpecified: Bool | |
var hasHeightSpecified: Bool | |
var alignment: Alignment = .center | |
init( | |
width: CGFloat? = nil, | |
height: CGFloat? = nil, | |
relativeTo style: Font.TextStyle, | |
alignment: Alignment = .center | |
) { | |
self._width = ScaledMetric(wrappedValue: width ?? 0, relativeTo: style) | |
self.hasWidthSpecified = width != nil | |
self._height = ScaledMetric(wrappedValue: height ?? 0, relativeTo: style) | |
self.hasHeightSpecified = height != nil | |
self.alignment = alignment | |
} | |
func body(content: Content) -> some View { | |
content.frame( | |
width: hasWidthSpecified ? width : nil, | |
height: hasHeightSpecified ? height : nil, | |
alignment: alignment | |
) | |
} | |
} | |
extension View { | |
func frame( | |
width: CGFloat? = nil, | |
height: CGFloat? = nil, | |
relativeTo style: Font.TextStyle, | |
alignment: Alignment = .center | |
) -> some View { | |
self.modifier(ScalingFrameModifier(width: width, height: height, relativeTo: style, alignment: alignment)) | |
} | |
func frame( | |
dimension: CGFloat?, | |
relativeTo style: Font.TextStyle, | |
alignment: Alignment = .center | |
) -> some View { | |
self.modifier(ScalingFrameModifier(width: dimension, height: dimension, relativeTo: style, alignment: alignment)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment