Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - stack multiple method calls in parent view

Tags:

swift

swiftui

I am kind of a SwiftUI newbe but my question is essentially this:
I have a view that looks like this:

struct myView: View {
    var label = Text("label")
    var subLabel = Text("sublabel")

    var body: some View {
        VStack {
            label
            subLabel
        }
    }

    public func primaryColor(color: Color) -> some View {
        var view = self
        view.label = view.label.foregroundColor(color)
        return view.id(UUID())
    }

    public func secondaryColor(color: Color) -> some View {
        var view = self
        view.subLabel = view.subLabel.foregroundColor(color)
        return view.id(UUID())
    }
}

And here is my problem:
In my parent view, I would like to call myView as follows

struct parentView: View {
    var body: some View {
        myView()
            .primaryColor(color: .red)
            .secondaryColor(color: .blue)
    }
}

Using only one of these modifiers works fine but stacking them won't work (since they return some View ?).
I don't think that I can use standard modifiers since I have to access myView variables, which (I think) wouldn't be possible by using a ViewModifier.
Is there any way to achieve my goal or am I going on the wrong direction ?

like image 713
Paul Avatar asked Feb 05 '26 14:02

Paul


1 Answers

Here is a solution for you - remove .id (it is really not needed, result will be a copy anyway):

struct myView: View {
    var label = Text("label")
    var subLabel = Text("sublabel")

    var body: some View {
        VStack {
            label
            subLabel
        }
    }

    public func primaryColor(color: Color) -> Self {
        var view = self
        view.label = view.label.foregroundColor(color)
        return view
    }

    public func secondaryColor(color: Color) -> Self {
        var view = self
        view.subLabel = view.subLabel.foregroundColor(color)
        return view
    }
}

and no changes in parent view

Demo prepared with Xcode 13 / iOS 15

demo

like image 58
Asperi Avatar answered Feb 07 '26 04:02

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!