Evan Nudd Evan Nudd - 1 month ago 8
Swift Question

Why is frame width of the view alway 600 by 600 with autolayout

I am making a basic Minesweeper app for practice / fun in swift. I want to make it so the size of the board (10 tiles wide) adapts to any iOS screen.

To do this I'm setting the size of each tile by getting my tileContainer view.frame.width and / 10.

My problem is that the tileContainer view is set to 600, no matter what. On my Storyboard I set the tileContainer equal to the width of the View Container, by CTR click & dragging to the view and selecting equal width. This keeps the width of tileContainer set at 600, regardless of the device I'm testing on. (which is my problem, width should change depending on screen width not a constant 600)

Does anyone know how I can get the proper width of the screen regardless of the device it's being used on?

Answer

When you are using auto-layout, the subviews are laid out after the viewDidLayoutSubviews function. Therefore, if you call tileContainer.frame.size before that, such as in viewDidLoad, it will always be 600 by 600 (which is the default size in storyboard).

viewDidLayoutSubviews: Called to notify the view controller that its view has just laid out its subviews. reference

override func viewDidLayoutSubviews() {
    print(tileContainer.frame.size); // This is actual size you are looking for
}
Comments