NEW: Learn to build the incredible iOS 15 Weather app today! >>

SOLVED: Passing Picker Value to a ForEach View: change number of Rectangles

Forums > SwiftUI

I would love to see as many solutions to this as possible: use a picker to select a value say from 2-10 and then draw that number of Rectangles. Trying to keep formatting minimal to make code as clear as possible. I think I need to create a struct or something, or two way binding... nevertheless have reached the end of my trial and error.

Note that I was able to create a Picker that changes an Int value! Yay. But in picture two you will see that changing the value doesn't change the number of Rectangles.

Picker works But Rectangles don't

import SwiftUI

struct PickerRectsTry: View {
    @State private var numberOfRectangles = 3
    let numbers = [Int](0...10)

    var body: some View {
        VStack {
            HStack {
                Picker("Number of Rectangles", selection: $numberOfRectangles) {
                    ForEach(0..<numbers.count) { index in
                        Text("\(self.numbers[index])")
                    }
                }
                .frame(width: 50).clipped()

                Text("\(numberOfRectangles)")
                    .foregroundColor(.blue)
            }

            // now how to pass numberOfRectangles - I think I need a struct or something
            HStack {
                ForEach(0..<numberOfRectangles, content: { index in
                    ZStack {
                        Rectangle().foregroundColor(.gray)
                        Text("\(index)")
                    }
                })
            }
        }
    }
}

   

I guess I don't know how to share an image, hopefully you get the point. https://ibb.co/PQsdg81

   

hi,

swapping out the second ForEach for this code that adds an explicit id: parameter should do the job:

ForEach(0..<numberOfRectangles, id: \.self) { index in
    ZStack {
        Rectangle().foregroundColor(.gray)
        Text("\(index)")
    }
}

(you can also simplify the earlier Text usage from Text("\(self.numbers[index])") to just Text("\(index)"))

hope that helps,

DMG

1      

Thank you @delawaremathguy. I can see how this works, and it does, so I appreciate that. I mostly understand I was being reduundant withi self.numbers . I somewhat understand why I had to add the explicit id. I less understand why I was using content in the first place. And I absolutely don't understand how the end parenthesis sort of worked in both places and sort of not. (That was my last catch as I implemented your solution in my project.) Is there anything you can tell me or place to direct me so that I can understand? You can see how far off I was assuming I needed to create a struct or something.

(I'm doing my best as homework is keeping track of all these different variations and shortened versions that do the same thing. Like Text("\(self.numbers[index])") to just Text("\(index)").

Next up I will be trying to add color pickers to change the fills in the first and last rectangles. But baby steps. Next I will try to get one of the color RGB variables stepping along this future array.

   

Here's the complete code that works, thanks again @delawaremathguy. Pick the number of Rectangles created in a Vertical Stack

struct PickerRectsTry: View {
    @State private var numberOfRectangles = 3
    let numbers = [Int](0...10)

    var body: some View {
        VStack {
            HStack {
                Picker("Number of Rectangles", selection: $numberOfRectangles) {
                    ForEach(0..<numbers.count) { index in
                        Text("\(index)")
                    }
                }
                .frame(width: 50).clipped()
            }

            VStack {
                ForEach(0..<numberOfRectangles, id: \.self) { index in
                    ZStack {
                        Rectangle().foregroundColor(.gray)
                        Text("\(index + 1)")
                    }
                }
            }
        }
    }
}

   

Hacking with Swift is sponsored by Essential Developer

SPONSORED Only until this Sunday, December 12th, you can join a free crash course to learn advanced techniques for testing new and legacy Swift code — it's the fast track to becoming a complete Senior iOS Developer!

Click to learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.