1

I'm new to Swift and I'd like to know how I can take some values from an array and turn them into buttons in a stack. I have an array with dogs and their info. I want the buttons to display the name of each dog. The number of dogs can change, so I need the stack to change to reflect what is in the array. I am really lost, I know I need to be adding this code to the view controller but I can't find anything similar to this

This is my array:

var myDogs = [
        Dog(name: "Saleks", gender: "Male", speed: 50),
        Dog(name: "Balto", gender: "Male", speed: 70),
        Dog(name: "Mila", gender: "Female", speed: 20)
    ]

This is my viewController:

    @IBOutlet weak var buttonsStack: UIStackView!

    override func viewDidLoad() {
        super.viewDidLoad()
        for Dog in myDogs {
        print("\(Dog.name)")
    }

//adding a new dog to the array

@IBAction func buyDogButton(_ sender: UIButton) {
func buyDog() {
myDogs.append(Dog(name: "Dogname", gender: "female", speed: 20))

}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
imeyer
  • 19
  • 6
  • Searching is always an option, does this answer your question? [Adding buttons programmatically to stackView in Swift](https://stackoverflow.com/questions/58162441/adding-buttons-programmatically-to-stackview-in-swift) – Joakim Danielson Jul 25 '20 at 13:55
  • Depending on the maximum number of dogs in the list, a table with a button in the cell might be an option also. – Runt8 Jul 25 '20 at 13:58

1 Answers1

2

I would do this:

So code would look like this (in view DidLoad):

var myDogs = [
              Dog(name: "Saleks", gender: "Male", speed: 50),
              Dog(name: "Balto", gender: "Male", speed: 70),
              Dog(name: "Mila", gender: "Female", speed: 20)
          ]

let stackView   = UIStackView(frame: CGRect(x: 40, y: 100, width: 60, height: 100))
stackView.backgroundColor = .red
stackView.axis  = NSLayoutConstraint.Axis.vertical
stackView.distribution  = UIStackView.Distribution.equalSpacing
stackView.alignment = UIStackView.Alignment.center
stackView.spacing   = 16.0
      
for dog in myDogs {
    let button = UIButton() // Need to set the IBAction
    button.setTitleColor(.blue, for: UIControl.State.normal)
    button.setTitle(dog.name, for: UIControl.State.normal)  // "Click"
    button.backgroundColor = .red
    stackView.addArrangedSubview(button)
 }

 stackView.translatesAutoresizingMaskIntoConstraints = false

 self.view.addSubview(stackView)
      //Constraints
 stackView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
 stackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true

I set background color to red to make buttons quite visible You may want to have button with common width, then set their frame when you create buttons.

claude31
  • 874
  • 6
  • 8