Im my application I have a StackView containing three different Views: Character, Starship and Vehicle.
Now, I would like that at a certain condition, just one View will appear and the other two won't.
I'm not saying hiding and showing, but installing and uninstalling. Why? because if I keep my views installed my Xcode crash.
Any tips?
I believe the answer you're looking for is here - https://stackoverflow.com/a/36712325/2463875
If You install or uninstall view from storyboard, It is equivalent to add/remove view.
I am not sure if I understand it 100% correctly.. But if you want to add views to a stackview programatically, you can do it kind of the following way. You need to connect the UIStackView to your ViewController to have access to it. There you can add your UIViews depending on a condition.
I've created a playground example. So you can just copy it and run it in a playground and it will also show it visually to you. To make it easier, I've used UILabels. But it's pretty much the same with UIViews.
import UIKit
import PlaygroundSupport
class TestViewController : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "Test"
self.view.frame = CGRect(x: 0, y: 0, width: 320, height: 480)
self.view.backgroundColor = UIColor.brown
let stackview = UIStackView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
stackview.axis = .vertical
stackview.distribution = UIStackViewDistribution.fillEqually
let text = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
text.text = "Hello, i am a label"
let condition = true
if condition {
let text2 = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
text2.text = "Hello, i am another label"
stackview.addArrangedSubview(text2)
}
stackview.addArrangedSubview(text)
self.view.addSubview(stackview)
}
}
let testController = TestViewController()
PlaygroundPage.current.liveView = testController.view
testController
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With