如何使用 swift 将元素添加到情节提要堆栈视图

how to add element using swift to a storyboard stackview

我是初学者,如果这是一个愚蠢的问题,我很抱歉,但我正在尝试将新元素添加到使用故事板制作的堆栈视图中。我想在每次按下按钮时都这样做,并且我想要相同的颜色、大小、约束...我该怎么做?

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

每次按下设置按钮时,我都想像其他按钮一样添加另一个按钮 请问,有人可以帮忙吗?

嗯,可以拿栈视图的IBOutlet连接。在这种情况下假设 stackView。

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

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

将您的堆栈视图连接到 @IBOutlet,例如:

@IBOutlet var stackView: UIStackView!

与其尝试“复制”您在 Storyboard 中设计的按钮,不如使用函数创建具有所需属性的新按钮:

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
}

现在,您点击“设置”按钮的功能可能如下所示:

@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 上面的代码假定了一个现有的函数来处理按钮操作——例如:

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