简体   繁体   中英

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?

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

Well, you can take the IBOutlet connection of the stack view. let say stackView in this case.

@IBOutlet var buttons : [UIButton]! // It will be a collection outlet of buttons (inside stack view).

self.stackView.subviews.forEach({$0.removeFromSuperview()})
buttons.append(UIButton())
buttons.forEach { (view) in self.stackView.addArrangedSubview(view) }
self.stackView.spacing = 12.0
self.stackView.distribution = .fillEqually
self.view.layoutIfNeeded()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM