Created
July 3, 2020 11:25
-
-
Save LeTarrask/a81459e26c60520598c5664f38ebd1b9 to your computer and use it in GitHub Desktop.
Common Swift APIs from https://samwize.com/2020/06/08/42-most-common-swiftui-api-modifiers-that-i-cant-remember/
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
| // Resizable image, fits in frame | |
| Image(systemName: "umbrella") | |
| .resizable() | |
| .aspectRatio(contentMode: .fit) | |
| .frame(width: 50, height: 50) | |
| //Increase hit area, including transparent area | |
| HStack { | |
| Text("When should you test yourself?") | |
| Spacer() // Without `contentShape`, this space is not hittable | |
| } | |
| .contentShape(Rectangle()) // Define hit testing | |
| .onTapGesture { ... } | |
| // Custom View Modifier | |
| struct MyModifer: ViewModifier { | |
| func body(content: Content) -> some View { | |
| // Do something with the content | |
| } | |
| } | |
| // Convenient method on View | |
| extension View { | |
| func myModifer() -> some View { | |
| self.modifier(MyModifer()) | |
| } | |
| } | |
| // Dismiss modal view | |
| @Environment(\.presentationMode) var presentationMode | |
| presentationMode.wrappedValue.dismiss() | |
| //Dismiss modal view 2 – the explicit way | |
| // In the presenter, | |
| @State private var isPresented = false // Declare an @State | |
| isPresented = true // when it's time to present | |
| .sheet(isPresented: $isPresented) { // The modal sheet uses the binding | |
| DeeperView(isPresented: self.$isPresented) // Also pass the binding to any children | |
| } | |
| // In the child views of the navigation stack, | |
| @Binding var isPresented: Bool // Declare the binding | |
| isPresented = false // when it's time to dismiss the modal for real | |
| //FIX Text truncating when it shouldn’t | |
| Text("Why the hell is this text truncated without reason?") | |
| .fixedSize(horizontal: false, vertical: true) // Workaround magic | |
| // Select an item using Picker in a Form | |
| // Assuming we have an enum to represent the list of items | |
| enum Side: CaseIterable { | |
| case wife, husband | |
| } | |
| @State var sideIndex = 0 | |
| Picker("Whose side you taking?", selection: $sideIndex) { | |
| ForEach(Side.allCases.indices) { | |
| Text(Side.allCases[$0].description) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment