Why the width of the view frame is always 600 by 600 with autostart

I am making the basic Minesweeper app for fast exercise / fun. I want to make the board size (10 tiles wide) adapt to any iOS screen.

To do this, I set the size of each tile, getting my tileContainer view.frame.width and / 10.

My problem is that tileContainer is set to 600, no matter what. On my storyboard, I set the tileContainer to be the width of the View Container by clicking on CTR and dragging it into the view and selecting equal width. So the tileContainer width is set to 600, regardless of the device I'm testing on. (this is my problem, the width should vary depending on the screen width not constant 600)

Does anyone know how I can get the correct screen width no matter which device it is used in?

+7
ios autolayout swift storyboard
source share
3 answers

When you use auto-layout, routines are laid out after the viewDidLayoutSubviews function. Therefore, if you call tileContainer.frame.size before, for example, in viewDidLoad , it will always be 600 by 600 (this is the default size in the storyboard).

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

 override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() print(tileContainer.frame.size); // This is actual size you are looking for } 
+16
source share

While the accepted answers are the correct answer, I thought I could at least say that you can make the object draw itself before clicking viewDidAppear :.

You can in your call viewDidLoad: ::

view.setNeedsLayout()
view.layoutIfNeeded()

Or, if you create it from "outside":

let vc = UIViewController()
let _ = vc.view

or

let vc = UIViewController()
vc.view.setNeedsLayout()
vc.view.layoutIfNeeded()

+3
source share

Short answer: UIScreen.mainScreen (). bounds.size.width always returns the width of the screen.

Long answer: it looks like you are using auto-layout with size classes. You can do all this only using restrictions. You can set the proportional width and height of the restriction from your tile to your container so that the tile is 10% of the width and height of the container. Then you can set all other tiles to equal width and height for one tile. Then use constraints to place them in the grid.

Another strategy that uses auto-detection is to set the cell spacing to 0 and leave unlimited width and height. If you have 10 cells with 0 spaces between cells and eachother and 0 spaces between the front and back cells and the container, then they will automatically take 1/10 of the width of the container.

Note that when using size / auto layout classes, the size of the view is not adjusted properly until the subselections are laid out, so if you try to make this width information in viewDidLoad, for example, the width will still be the width of any type (600).

+2
source share

All Articles