Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Swift: Install and Unistall views programmatically

How to install and uninstall views programmatically?

Example

Im my application I have a StackView containing three different Views: Character, Starship and Vehicle.

enter image description here

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.

enter image description here

Any tips?

like image 521
Andrea Miotto Avatar asked Oct 25 '16 12:10

Andrea Miotto


Video Answer


2 Answers

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.

like image 96
Aviv Ben Shabat Avatar answered Oct 01 '22 00:10

Aviv Ben Shabat


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
like image 30
Prine Avatar answered Sep 30 '22 23:09

Prine