Created
March 5, 2020 14:27
-
-
Save HarshilShah/205fa2d7a003fbde896f6f34a2336557 to your computer and use it in GitHub Desktop.
A basic attempt at recreating the Form SwiftUI component on macOS
This file contains hidden or 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 | |
| struct LabeledViewAlignment: AlignmentID { | |
| static func defaultValue(in context: ViewDimensions) -> CGFloat { | |
| context[.leading] | |
| } | |
| } | |
| extension HorizontalAlignment { | |
| static let labeledViewAlignment = HorizontalAlignment(LabeledViewAlignment.self) | |
| } | |
| struct LabeledView<Content: View>: View { | |
| var label: String | |
| var content: Content | |
| init(label: String, @ViewBuilder builder: () -> Content) { | |
| self.label = label | |
| self.content = builder() | |
| } | |
| var body: some View { | |
| HStack(alignment: .firstTextBaseline) { | |
| Text(label) | |
| .multilineTextAlignment(.trailing) | |
| content | |
| .alignmentGuide(.labeledViewAlignment) { dimensions in | |
| dimensions[.leading] | |
| } | |
| } | |
| } | |
| } | |
| struct LabelModifier: ViewModifier { | |
| var label: String | |
| func body(content: Content) -> some View { | |
| LabeledView(label: label) { | |
| content | |
| } | |
| } | |
| } | |
| extension View { | |
| func labeled(_ label: String) -> some View { | |
| self.modifier(LabelModifier(label: label)) | |
| } | |
| } | |
| struct LabeledContainer<Content: View>: View { | |
| var content: Content | |
| init(@ViewBuilder builder: () -> Content) { | |
| self.content = builder() | |
| } | |
| var body: some View { | |
| VStack(alignment: .labeledViewAlignment, spacing: 0) { | |
| content | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment