Search code examples
iosswiftuiviewautolayoutautoresizingmask

What happens when I programatically add a subview without constraints?


I have frequently came across something like view.addSubview(myAwesomeTableView).

Obviously, there are no constraints set in Auto Layout. So how does the system determine how and where to place myAwesomeTableView. Will it simply match the size of the parent view?

Also what does translatesAutoresizingMaskIntoConstraints have to do with this?


Solution

  • So how does the system determine how and where to place myAwesomeTableView. Will it simply match the size of the parent view?


    basically, it depends on myAwesomeTableView (the subview) frame. When adding a subview, it would automatically added at (0,0) origin, so the subview frame would be:

    x: 0
    y: 0
    width: subview width.
    height: subview height.
    

    Note that if the subview frame is undetermined, the width and the height are 0 by default.


    what does translatesAutoresizingMaskIntoConstraints have to do with this?


    Adapted from translatesAutoresizingMaskIntoConstraints documentation:

    A Boolean value that determines whether the view’s autoresizing mask is translated into Auto Layout constraints.

    That means it would the system creates a set of constraints that duplicate the behavior specified by the view’s autoresizing mask, you would be able to directly modify the desired view location (origin) and size by editing its frame value.

    Note that:

    By default, the property is set to true for any view you programmatically create. If you add views in Interface Builder, the system automatically sets this property to false.

    When it comes to adding constraints to the view programmatically, note that you have to set translatesAutoresizingMaskIntoConstraints to false:

    myView.translatesAutoresizingMaskIntoConstraints = false
    

    means that "I will handle the constraint of the view by my self", otherwise the added constraints would not be activated.

    Furthermore, you might want to check: