繁体   English   中英

如何使用 swift 将元素添加到 storyboard 堆栈视图

[英]how to add element using swift to a storyboard stackview

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

这是我的代码的图像

这是我的 storyboard 结构的图像

这就是我用 storyboard 做的

我想在每次按下设置按钮时添加另一个按钮,有人可以帮忙吗?

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

@IBOutlet var stackView: UIStackView!

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

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
}

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

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

编辑上面的代码假设现有的 function 用于处理按钮操作 - 例如:

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

好吧,你可以拿堆栈视图的IBOutlet连接。 在这种情况下,让我们说 stackView 。

@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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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