Reputation: 13943
How can I retrieve the calculated height/width of a UIView
is the height and/or width was let using a NSConstraint
?
To explain differently:
I would like to retrieve the CGFloat
value of a UIView's
"width" or "height" after the element has been laid out using autolayout and constraints.
Upvotes: 2
Views: 1962
Reputation: 26913
Provided a view is constrained, you can get its “fitting” size using:
let size = view.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
If you get invalid values then your view is not constrained or you are calling it before its parent has been laid-out.
Upvotes: 0
Reputation: 3494
There is no particular point when you are certain your views were completely laid out by the layout system. But there are some methods that are being called after each layout cycle.
So if your textField
is a custom class or part of a custom UIView
, like a UITableViewCell
, this method would be layoutSubviews
. In this care you can get the size using the following code:
override func layoutSubviews() {
super.layoutSubviews()
textWidth = textField.frame.width
textHeight = textField.frame.height
}
This code will give you the right values every time something changes in they layout(like orientation change or some other elements changed their frames or constraints).
If you dont have a custom view, but you are using the textField straight in a UIViewController
, the method is viewDidLayoutSubviews
. This gets called after the viewController completes layout of the entire view hierarchy.
override func viewDidLayoutSubviews() {
super.layoutSubviews()
textWidth = textField.frame.width
textHeight = textField.frame.height
}
Let me know if I can help you further or if you have more questions. Hope this helps with your implementation.
Upvotes: 2
Reputation: 3875
Here is how you can get height & widht depending on content of the view
let adjustedWidth = anyView.intrinsicContentSize.width
let adjustedHeight = anyView.intrinsicContentSize.height
Upvotes: 1