Last active
March 31, 2023 07:38
-
-
Save josippetric/da699cd8235d8f6860d57706a5ede2f7 to your computer and use it in GitHub Desktop.
SwiftUI Helpers
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 | |
| // Overload that allows some bindings to be optional. E.g. having an optional | |
| // property bound to the TextField | |
| // TextField("", text: $optionalProperty ?? "default value") | |
| func ??<T>(lhs: Binding<Optional<T>>, rhs: T) -> Binding<T> { | |
| Binding( | |
| get: { lhs.wrappedValue ?? rhs }, | |
| set: { lhs.wrappedValue = $0 } | |
| ) | |
| } | |
| //// BINDING EXTENSION | |
| extension Binding { | |
| func onChange(_ handler: @escaping (Value) -> Void) -> Binding<Value> { | |
| Binding( | |
| get: { self.wrappedValue }, | |
| set: { newValue in | |
| self.wrappedValue = newValue | |
| handler(newValue) | |
| } | |
| ) | |
| } | |
| } | |
| // Example usage of onChange extension | |
| TextField("Your name:", text: $name.onChange(nameChanged) | |
| func nameChanged(to newValue: String) { | |
| // Do something when name has been changed | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment