Search code examples
iosswiftstoryboard

how to add element using swift to a storyboard stackview


I am a beginner so sorry if it is a stupid question but I am trying to add new elements to a stack view that was made with a storyboard. I want to do it every time a button was pressed and I want the same color, size, constraint... how do I do this?

here is an image of my code

and this is the image of my storyboard structure

and this is what I made with the storyboard

and I want to add another button like the other ones every time the settings button is pressed pls, can anyone help?


Solution

  • Connect your stack view to an @IBOutlet such as:

    @IBOutlet var stackView: UIStackView!
    

    Instead of trying to "copy" the button you designed in Storyboard, use a function to create a new button with your desired properties:

    func makeNewButton() -> UIButton {
        // create a button
        let b = UIButton()
        // set your desired font
        b.titleLabel?.font = .systemFont(ofSize: 18.0, weight: .light)
        // set background color to your desired light-green
        b.backgroundColor = UIColor(red: 0.0, green: 0.85, blue: 0.0, alpha: 1.0)
        // set title colors for normal and highlighted
        b.setTitleColor(.white, for: .normal)
        b.setTitleColor(.gray, for: .highlighted)
        return b
    }
    

    Now, your function for tapping the "Settings" button could look like this:

    @IBAction func settingsButtonPressed(_ sender: Any) {
        // call func that returns a new button with your
        //  desired colors, font, etc
        let newButton = makeNewButton()
        // set the title (presumably you'll be getting a new title string from somewhere)
        newButton.setTitle("New Button", for: [])
        // give it an action
        newButton.addTarget(self, action: #selector(self.btnTapped(_:)), for: .touchUpInside)
        // add it to the stack view
        stackView.addArrangedSubview(newButton)
    }
    

    Edit the above code assumed an existing function for handling the button action - such as:

    @objc func btnTapped(_ sender: UIButton) {
        // do something when the button is tapped
        print("A button was tapped...")
    }