我目前正在尝试制作一个简单的应用程序,该应用程序将根据用户的输入显示少量内容。目前,我的屏幕上有一个堆栈视图,其中有一个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的新手。
答案 0 :(得分:2)
尝试一下:
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)
}
}
答案 1 :(得分:1)
首先,您的门店应该位于顶层:
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
}
}
答案 2 :(得分:0)
在外部类范围内声明出口函数
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
}
}