以编程方式编辑 UIStackView



>我目前正在尝试制作一个简单的应用程序,该应用程序将根据用户的输入显示少量内容。目前,我的屏幕上有一个堆栈视图,里面有一个 UIView。我正在尝试使一旦按下一个按钮,UIView 就会消失,然后当按下另一个按钮时,会出现一个新按钮。该按钮可以继续按下,更多视图将放入堆栈视图中。

这是我目前拥有的,它不起作用,我不知道在寻找一段时间的答案后如何让它工作:

import UIKit
class ViewController: UIViewController {

@IBAction func deleteButtonPressed(_ button: PushButton) {

@IBOutlet weak var containerStackView: UIStackView!
containerStackView = UIStackView(arrangedSubviews: [removeIcons()])
}
func removeIcons() -> UIView {
let newView = UIView(frame: CGRect(x: 0, y:0, width: 100, height: 100))
return newView
}
}

有没有办法引用堆栈视图然后更改它?

----编辑

我现在有这个代码:

class ViewController: UIViewController {
@IBOutlet var containerStackView: UIStackView!
@IBAction func deleteButtonPressed(_ sender: Any) {
let newView = UIView(frame: CGRect(x: 0, y:0, width: 100, height: 100))
newView.backgroundColor = UIColor.black

containerStackView = UIStackView(arrangedSubviews: [newView])
}
}

这似乎完美地代表了堆栈视图,但是,当我按下按钮时,堆栈视图似乎没有任何反应。从理论上讲,当前存在的UIView应该被一个创建为"newView"的小黑色方块所取代。虽然这似乎没有发生 - 我错过了什么明显的东西吗?

很抱歉这些问题,我是 swift 和 xcode 的新手。

试试这个:

class ViewController: UIViewController {
//...
@IBOutlet weak var containerStackView: UIStackView!
//...
@IBAction func deleteButtonPressed(_ button: PushButton) {
let newView = UIView(frame: CGRect(x: 0, y:0, width: 100, height: 100))
containerStackView.addArrangedSubview(newView)
}
}

首先,您的出口应该位于顶层:

import UIKit
class ViewController: UIViewController {
@IBOutlet weak var containerStackView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func deleteButtonPressed(_ button: PushButton) {
containerStackView = UIStackView(arrangedSubviews: [removeIcons()])
}
func removeIcons() -> UIView {
let newView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
return newView
}
}

在类范围之外的函数旁边声明出口

class ViewController: UIViewController {
@IBOutlet weak var containerStackView: UIStackView! // here
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func deleteButtonPressed(_ button: PushButton) {
containerStackView.subviews.forEach { $0.removeFromsuperView() }
}
@IBAction func daddButtonPressed(_ button: UIButton) {
containerStackView = UIStackView(arrangedSubviews: [removeIcons()])
}
func removeIcons() -> UIView {
let newView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
return newView
}
}

最新更新