Skip to content

Instantly share code, notes, and snippets.

@javalnanda
Created February 6, 2024 07:57
Show Gist options
  • Save javalnanda/1f23107bf9a7cd0888c6e3cc99c4d975 to your computer and use it in GitHub Desktop.
Save javalnanda/1f23107bf9a7cd0888c6e3cc99c4d975 to your computer and use it in GitHub Desktop.
SwiftUI View Extensions
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