Created
February 6, 2024 07:57
-
-
Save javalnanda/1f23107bf9a7cd0888c6e3cc99c4d975 to your computer and use it in GitHub Desktop.
SwiftUI View Extensions
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
import SwiftUI | |
public extension View { | |
func fillMaxSize(alignment: Alignment = .center) -> some View { | |
frame(maxWidth: .infinity, maxHeight: .infinity, alignment: alignment) | |
} | |
func fillMaxWidth(alignment: Alignment = .center) -> some View { | |
frame(maxWidth: .infinity, alignment: alignment) | |
} | |
func fillMaxHeight(alignment: Alignment = .center) -> some View { | |
frame(maxHeight: .infinity, alignment: alignment) | |
} | |
func size(_ size: CGFloat, alignment: Alignment = .center) -> some View { | |
frame(width: size, height: size, alignment: alignment) | |
} | |
func height(_ height: CGFloat) -> some View { | |
frame(height: height) | |
} | |
func width(_ width: CGFloat) -> some View { | |
frame(width: width) | |
} | |
func padding(paddings: Paddings) -> some View { | |
padding( | |
EdgeInsets(top: paddings.top, leading: paddings.leading, bottom: paddings.bottom, trailing: paddings.trailing) | |
) | |
} | |
/// Returns the size of the view after drawing, so it can be stored in a @State variable and used to fit other views | |
func readSize(onChange: @escaping (CGSize) -> Void) -> some View { | |
background( | |
GeometryReader { geometryProxy in | |
Color.clear | |
.preference(key: SizePreferenceKey.self, value: geometryProxy.size) | |
} | |
) | |
.onPreferenceChange(SizePreferenceKey.self, perform: onChange) | |
} | |
} | |
private struct SizePreferenceKey: PreferenceKey { | |
static var defaultValue: CGSize = .zero | |
static func reduce(value _: inout CGSize, nextValue _: () -> CGSize) {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment