UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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)")
                    }
                })
            }
        }
    }
}

3      

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

3      

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

4      

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.

3      

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)")
                    }
                }
            }
        }
    }
}

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.