[英]how to add element using swift to a storyboard stackview
如果這是一個愚蠢的問題,我很抱歉,但我正在嘗試將新元素添加到使用 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.