I’m trying to add an extension to modify the behavior of a custom swiftui view, similar to what you do with the disabled extension function:
Button("Title") { do something }
.disabled(true)
I will oversimplify what Im trying to do with the code below, (comments in line).
// The custom view is a horizontal paging view, for simplicity I just added a Stack with the value of a @State variable that would change the behavior to disable scrolling.
struct MyHorizontalScroll: View {
@State fileprivate var disableScroll = false
var body: some View {
HStack {
Text("Disable Scroll: (disableScroll)")
.font(.title)
}
}
}
In this extension I add a method called disableScroll that should allow the caller to either disable or enable the scroll
extension MyHorizontalScroll {
func disableScroll(_ disable: Bool) -> some View {
self.disableScroll = disable
// /Note that the disableScroll state variable does not change doesn't matter what I try to set. I've tried setting it directly with self._disableScroll.wrappedValue with the same results.
// The only thing that works is to copy the view variable and create a new State variable and setting it directly like this:
/*
var view = self
view._disableScroll = State(initialValue: disable)
return view
*/
// The commented code above works, but I'm not sure this would be the right thing to do.
return self
}
}
An example of the pattern usage.
struct ContentView: View {
var body: some View {
VStack {
MyHorizontalScroll()
.disableScroll(true)
}
.padding()
}
}
I know I can use a @Bindable variable, but I like the extension modifier pattern. Is there a way to achieve this behavior change with this pattern?