I have a tableView between a label which is on top (constraints: align center x, align top to 20).
A button is on the bottom (constraints: align center x, align bottom to 50).
And the tableView is aligned between those two objects by top/bottom to 20.
I am trying to read out the height of the tableView, because depending which device I use the height should differ? But if I use in my code the following, I always get the same height for the tableView.
The print result is always 616.
What am I missing/not understanding correctly?
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
print(tableView.frame.size.height)
}
CodePudding user response:
try getting your height in
override func viewWillLayoutSubviews() {
print(tableView.frame.size.height)
}
CodePudding user response:
When your view controller is created from a storyboard, all initial frames are equal to your storyboard selected ones, so they will be correct only to device selected in the storyboard
First time you can access real frames is after first layoutSubviews
, so you need this:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
print(tableView.frame.size.height)
}
Check out more about view lifecycle here
p.s. newer forget to call super.
method when you're overriding something, you may break something easily. Unless the documentation says so or you're really knowing what you're doing
CodePudding user response:
Try this method
override func viewWillLayoutSubviews() {
super.viewDidLayoutSubviews()
print(tableView.frame.size.height)
}
The reason that you see two different values printed is because this method is called right after viewdidload and once again after all the auto layout or auto resizing calculations on the views have been applied. Meaning the method viewDidLayoutSubviews is called every time the view size changes and the view layout has been recalculated.
For more info on this refer to
Apple documentation on viewdidlayoutsubviews