Search code examples
iosswiftuiviewsubviewaddsubview

Are UIViews duplicated when adding a subview again in Swift?


I am wondering something about UIView, and adding subviews...

So say I add a subview to a baseLayerView as so:

  self.newBaseLayer.addSubview(self.usernameLabel)

The UIView hierarchy/structure will, correct me if I'm wrong, like this:

  • newBaseLayer

    • self.usernameLabel

And then later in the code, I add another subview:

  self.newBaseLayer.addSubview(self.dateLabel)

And finally I add again the username label:

  self.newBaseLayer.addSubview(self.usernameLabel)

Will the usernameLabel duplicate or replace the other like so:

  • newBaseLayer

    • self.usernameLabel
    • self.dateLabel
    • self.usernameLabel

or

  • newBaseLayer

    • self.dateLabel
    • self.usernameLabel

Solution

  • I guess we are talking about UIViews and not Layers here?!

    In this case usernameLabel is just added once even if you call addSubview multiple times.

    To avoid any ambiguity here some code:

    let baseView = UIView()
    let dateLabel = UILabel()
    let usernameLabel = UILabel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        baseView.tag = 1
        usernameLabel.tag = 2
        dateLabel.tag = 3
    
        self.view.addSubview(self.baseView)
    
        self.baseView.addSubview(self.usernameLabel)
        self.baseView.addSubview(self.dateLabel)
        self.baseView.addSubview(self.usernameLabel)
    
        self.traverseViewHierarchy(view: self.baseView, level: 0)
    
    }
    
    private func traverseViewHierarchy(view: UIView, level: Int) {
        for _ in 0...level {
            print (" | ", terminator: "")
        }
        print ("view: \(view.tag)")
        for view in view.subviews {
            self.traverseViewHierarchy(view: view, level: level + 1)
        }
    }
    

    This add some tags to the mention views and gives it out in the console:

    | view: 1
    |  | view: 3
    |  | view: 2
    

    As you can see usernameLabel is just added once to the view hierarchy.