Quantm Quantm - 11 months ago 67
Swift Question

Custom View - self.frame is not correct?

So I have a custom UIView class

class MessageBox: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
func createSubViews() {

let testView = UIView(frame: self.frame)
testView.backgroundColor = UIColor.brown

I added a UIView inside the storyboard and gave it some constraints:

100 from the top (superview), 0 from the left and right, height is 180

But when I run the app the brown subview I created in the code is way to big. I printed
in my custom view and it turns out that the frame is
. But why? I set constraints, it should be something like
(0,0,deviceWith, 180)

enter image description here

What did I do wrong?

EDIT: That's my Storyboard setup:

enter image description here

Answer Source

Short and simple answer:

You're doing it too early.

Detailed answer:

When a view is initialized from an Interface Builder file (a xib or a storyboard) its frame is initially set to the frame it has in Interface Builder. You can look at it as a temporary placeholder.

When using Auto Layout the constraints are resolved (= the view's actual frame is computed) inside the view's layoutSubviews() method.

Thus, there are two possible solutions for your problem:

  1. (preferrable) If you use Auto Layout, use it throughout your view.

    • Either add your testView in Interface Builder as well and create an outlet for it
    • or create your testView in code as you do, then set its translatesAutoResizingMaskIntoConstraints property to false (to sort of "activate Auto Layout") and add the required constraints for it in code.
  2. Set your testView's frame after the MessageBox view's frame itself has been set by the layout engine. The only place where you can be sure that the system has resolved the view's frame from the constraints is when layoutSubviews() is called.

    func override layoutSubviews() {
        testView.frame = self.frame

    (You need to declare your testView as a property / global variable, of course.)