Hi guys,
I'm so stuck on a problem that was super easy in UIKit, but seemingly impossible in SwiftUI.
All I need to do is create reusable controls that have logic and view encapsulation, and can validate on every key pressed. These controls do different things like validate text input in a special way, or calculate different things, and in UIKit it was easy, I would just make a class to handle the logic and the view, drop them into my project either programatically or via storyboard, and they'd do their thing. I'd like to do the same in SwiftUI by encapsulating a control so that I can do something like this:
@ObservedObject var vm = FormViewModel()
VStack {
ControlType1(minLength: 5, allowsDecimal: false, text: $vm.userID)
ControlType2(maxLength 3, allowsUnicode: true, text: $vm.frpReading)
//Etc
}
I have scoured all over the internet for months and cannot find a good way to encapsulate the logic with a view. It seems like no one else has either and there are plenty of people trying to do this same thing. It's very common to do in the enterprise world. I just want to be able to instantiate a control with some settable properties and have it handle my logic.
ViewModels looked promising, but if a ViewModel is controlling the logic of one of those ControlType views and massaging the input string, then there is no way to connect the data to the FormViewModel which oversees the logic of the entire form.
Combine sounded promising but it's such a nightmare syntax wise and the documentation for it is virtually non-existent.
Property Observers don't work the same when it comes to @Published and other property wrappers so they're out the window. You get either nothing, or infinite loops when you try and use them in SwiftUI.
My question is, how can I create a reusable component that lets me handle logic every time a key is pressed? This took minutes in UIKit. Is it even possible in SwiftUI yet?