Reputation: 352
I'm running my app on my iPhone 6 plus which has a screen width of 414 points, if I set the preview device to iPhone 7 which has a screen width of 375 points, when the table is first loaded, I printed out the size of the table in viewdidload and it had a width of 414, but the table cells all had a width of 375, after I scrolled up and back, the width changed to 414. Tested in multiple UITableViewController, all gave the same result.
My questions are:
Why is the size of the table view cell dependent on the preview device size?
how do I make the cell have the correct size when it's first loaded?
tableView.layoutIfNeeded(), tableView.layoutSubViews() don't work.
Upvotes: 1
Views: 1090
Reputation: 352
The tableview has the correct size 414 (my device size) but somehow the cell size is the size of the simulated metrics, after a couple months of researching, this is the answer I came up with:
In my cell class, override awakeFromNib()
, set frame.size.width
to UIScreen.main.bounds.width
, then call layoutIfNeed()
Upvotes: 6
Reputation: 804
Every time a view is loaded from Storyboard, it will initially have EXACTLY the size that was specified in the storyboard, then when it's added to the view hierarchy, its frame will be adjusted (either by Autolayout or your custom code).
So in your case, when a cell is first loaded from storyboard, it will have 414 point in width (assumingly your tableView has the same width with the view controller), but when it is put in the actually view hierarchy, it will be resized accordingly (375pt, which is equal to your tableview's width).
Upvotes: 0