iOS Swift: Install and Unistall views programmatically

swift, uiview, xcode

Solution

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

Problem

How to install and uninstall views programmatically? Example 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?

Original source

Related problems