0

I'm a former webdesigner starting to learn native app design with SwiftUI.

I have a problem : I want to add a component to an HStack each time I click on a dedicated button.

Multiple questions :

  • Can I stock a value in a component (SwitUI View) and read it from another view ? (Lets say, one component value is "4" and a second component value is "6", I want to be able to read these values in order to display a total of "10")

  • How can I append a component into my HStack when I click my button ?

Thanks in advance !

2 Answers 2

1

Can I stock a value in a component (SwitUI View) and read it from another view ? (Lets say, one component value is "4" and a second component value is "6", I want to be able to read these values in order to display a total of "10")

See the answers at the below url. Hope that helps you get started.

How to access to a variable in another struct? SWIFTUI

How can I append a component into my HStack when I click my button ?

You can have a ForEach that loops a card array variable (as State or ObservableObject) to create the CardView. Appending to the array, would refresh the view. Here's some example code.

import SwiftUI

class Card: NSObject {
    var id: Int
    var name: String

    init(id: Int, name: String) {
        self.id = id
        self.name = name
    }
}

class Model: ObservableObject {
    @Published var cards: [Card] = []

    init() {
        cards = [
            Card(id: 1, name: "Card 1"),
            Card(id: 2, name: "Card 2"),
            Card(id: 3, name: "Card 3")
        ]
    }

}

struct ContentView: View {
    @ObservedObject var model = Model()

    var body: some View {
        NavigationView {
            List {
                ForEach(model.cards, id: \.self) { card in
                    Text("\(card.name)")
                }
                Spacer()
            }
            .padding()
            .navigationBarItems(trailing:
                Button(action: self.addCard) {
                    Image(systemName: "plus")
                }
            )
        }
        .navigationBarTitle("Cards")
    }

    private func addCard() {
        let id = model.cards.count + 1
        model.cards.append(Card(id: id, name: "New Card \(id)"))
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, I'll check your anwser :) For the append question : I need to be able to add on component multiple time on a dedicated part of my view, let say I have a playing card and I want to add that card multiple time, have a stack of cards on the top of my view. So I want something like this : HStack { MyComponent() MyComponent() MyComponent() //and be able to add several "MyComponent()" here by clicking a button } Hope this is clearer :)
It's still all fresh to me, may I ask an exemple or a link to help me create this loop ? Thanks again !
Added code that shows the usage of ObservableObject, Published & ObservedObject. Using these you can add views to an existing stack.
I tried to retrieve a var value from another struct using @Binding as you show in the other thread but I have this error in the "ContentView_Previews" struct : ContentView() Missing argument for parameter 'myValue' in call . (I wrote "@Binding var myValue: Int" in the beginning of my struct)
For the preview, you can pass a constant using the syntax .constant(intValue). i.e. ContentView(myValue: .constant(1))
|
0

Can I stock a value in a component (SwitUI View) and read it from another view ? (Lets say, one component value is "4" and a second component value is "6", I want to be able to read these values in order to display a total of "10")

You could use an EnvironmentObject or a singleton pattern so you are able to access your variables from both views. An other option is passing the variables as an argument to the second view

9 Comments

Refering to your answer on the other post: In the case of an MyElement() you could of course use an @State var myElements: [MyElement] = []. Then you just need to put self.myElements.append(MyElement())in the button's action an myElements[indexNumber]in the ForEach loop
My write : ForEach (0..<(stringArray.count)) {indexNumber in myElements[indexNumber] } But it asked me to add a "self." before myElements[indexNumber]. And with the self I have no error but nothing appear when clicking the button, any idea ? Thanks again !
You're using the stringArray.count, but the element comes from the myElementsarray. Maybe that's the problem? Could you post your complete struct please?
import SwiftUI struct ContentView: View {@State var MyArray: [Component] = [] var body: some View { VStack { HStack { ZStack { ForEach (0..<(MyArray.count)) {indexNumber in self.MyArray[indexNumber] } } } Button(action: { self.MyArray.append(Component()) }) } } }
First of all, in this case you don't need the ZStack. The VStack lets the Button appear under your HStack which should contain your own views. If you want to add an own element/an own component to the stack, you need to create your own view, I think you already did that with Component. Of course your component view needs some content, otherwise you keep adding empty views to your stack. In addition, your button has no label, so you aren't able to see it. I'll post an example code in my existing answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.