Bounds and Frame deliver Wrong Value in iOS - ios

I have a label in a View Controller scene inside a root view.
I set the constraint of the height to 30 using the Pins button right below.
Everything looks pretty in the storyboard.
But when I want to get the size of the element inside my code I always get the value 21. I tried refLabel.bounds.size.height and refLabel.frame.height. I call this in the override func viewDidLoad(){
super.viewDidLoad() function of the corresponding class.
Has this something to do with the intrinsic content size?

Try this code
refLabel.layoutIfNeeded()
let height = refLabel.frame.size.height
print("right height is \(height)")

Related

How to corrently use UIViews systemLayoutSizeFitting to get the height to show all subviews using a given width?

TD;DR
It seems that in some cases systemLayoutSizeFitting does not return the correct height to correctly show / position all subviews of a view. Am I using systemLayoutSizeFitting wrong or is there some other way to avoid this?
Long story:
The XIB file of a UIViewController does not only contain the main view but also a number of other views which are added to the view controllers view at runtime. All these additional views should get the same height when they are added to the view controllers view.
The views might look like this: A simple container view holding some subviews which are stacked on top of each other.
Since the height of the container view should be flexible, the vertical spacing between the bottom button and the lable above it, uses a grater-than constraint.
To give all views the same height, I tried to measure the necessary height of each view using systemLayoutSizeFitting:
#IBOutlet var pageViews: [UIView]!
override func viewDidLoad() {
super.viewDidLoad()
var maxHeight: CGFloat = 0
for pageView in pageViews {
// Add pageView somewhere on view and give it leading, trailing and top
// constraint, but no height constraint yet.
addToView(pageView)
maxHeight = max(maxHeight, pageView.systemLayoutSizeFitting(CGSize(width: view.frame.width, height: UIView.layoutFittingCompressedSize.height), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel).height)
}
for pageView in pageViews {
// Give all pageViews the same height
pageView.heightAnchor.constraint(equalToConstant: maxHeight).isActive = true
}
}
This does not work, when the label text becomes to long:
In the right example the height is not large enough and thus the button is squeezed. I can counter act this by raising the vertical compression resistance of the button, however in this case the other controls (e.g. the title label) is squeezed...
Why is this? Why does not systemLayoutSizeFitting return a height which is sufficent to show all controls without any squeezing?
Its actually smash button's height when label text is getting bigger . You are setting top and bottom constraints but button height is not declared so when label getting bigger , view basically say "I can reduce button height before updating my height , I have space.Bottom and top constraints are still same , didn't effect."
Giving the constant height constraints of button might be fix your issue.
If you want your view to resist to compression you should use the defaultHigh priority as a verticalFittingPriority instead of fittingSizeLevel.

how to change view controller width size programatically?

I am trying to make a viewcontroller manually without using pod following this tutorial https://www.youtube.com/watch?v=Hl_Re_KLhcY&t=141s
but the sideMenuVC (the green one) has width that set accurately, I mean, the sideMenuVC should be 80% of the size of MainMenuVC. so if I change from iPhone 5s to iPhoneX, the autolayout still look perfect. But this is what I get
the sideMenuVC should be 80% only, but it looks full size on iPhone 5s
in sideMenuVC viewDidLoad I want to set something like this
class SideMenuVC: UIViewController {
#IBOutlet var sideMenu: UIView!
override func viewDidLoad() {
super.viewDidLoad()
sideMenu.frame.width = self.view.frame.width / 2
}
}
but it doesn't work since it is get only property
so I want to change the width in here
What you would optimally want to achieve your desired output is keep the view controller's width as is, but add a normal view inside with the following constraints
Leading to superview with a constant value of 0
Top to superview with a constant value of 0
Bottom to superview with a constant value of 0
Width equal to superview with a multiplier value of 4:5
You also need to set the background color of the UIViewController's default view property to .clear.
Finally, set the presentation style of that newly created UIViewController to Over Current Context.
When presenting a view controller using the UIModalPresentationFullScreen style, UIKit normally removes the views of the underlying view controller after the transition animations finish. You can prevent the removal of those views by specifying the UIModalPresentationOverCurrentContext style instead. You might use that style when the presented view controller has transparent areas that let underlying content show through.

Swift 3: Get distance of button to bottom of screen

I want to get the distance of a button to the bottom of the screen in Swift 3.
I can see the correct value in the Storyboard when I look at the distance (alt key) but unfortunately I am not able to calculate it manually.
The value I am looking for is the same as the constant in the "Vertical Spacing to Bottom Layout" constraint for the button.
view.frame.maxY - randomButton.frame.maxY
gave me a value way too high.
view.frame.size.height - (button.frame.size.height + button.frame.origin.y)
I think its ok! Hope it helps
If your button is not a direct successor of the view controller's view (aka, the hierarchy is something like ViewController's View -> SomeOtherView->Button), you won't get the right math by simply using frames. You will have to translate the button's Y-position to the coordinate space of the window object or your view controller's main view.
Take a look at this question: Convert a UIView origin point to its Window coordinate system
let realOrigin = someView.convert(button.frame.origin, to: self.view)
Then apply the math suggested by Lucas Palaian.
let bottomSpace = view.frame.maxY - (button.frame.height + realOrigin.y)
Another work around, in case something really wild and wierd is going on there, is to drag and drop an outlet of the button's bottom constraint. (Select the constraint from the view hierarchy in Interface Builder, hold the control key and drag the constraint to your view controller.) Then in your code you can access the constant.
let bottomSpace = myButtonBottomConstraint.constant
Use this to have it from the bottom of the button to the bottom of the view (Tested):
view.frame.size.height - randomButton.frame.size.height/2 - randomButton.frame.origin.y
I needed to find the distance from the bottom edge of the UICollectionView
to the bottom edge of the screen.
This code works for me:
#IBOutlet weak var collectionView: UICollectionView!
private var bottomSpace = CGFloat()
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
bottomSpace = UIScreen.main.bounds.height - collectionView.frame.maxY
}
This method is called several times it gives the correct result.

How to prevent UILabel to fill the entire screen?

I am trying to display a UILabel that may take up multiple lines but I'm having problem with how the height is resized.
Here is what it looks when I have text over a single line, displaying correctly:
When the text spans multiple lines however this happens:
Here's the interface builder settings I'm using:
Ideally I'd like the text view to remain at athe top of the screen and just take up as much space as it needs to diaplay the text but I really can't tell where I am going wrong.
The text view is a bit tricky to handle with automatic layout. If possible use an UILabel. If not then there are several issues with the text view and the most manageable solution is to add the height constraint which is then manipulated in the code.
The height of the text view content can be determined as:
let height = textView.sizeThatFits(textView.frame.size).height
It is also possible to use
let height = textView.contentSize.height
But the results are sometimes incorrect.
You do need to then set the delegate for the text view so that on change you will refresh the size of the text view.
Well you did give it permission to do so based on your constraints. Any height > 0 as long as it's 20 from the top margin. Since you don't have any other views to base your height off of you can hook up an outlet to your label and use this:
#IBOutlet weak var label: UILabel!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
label.sizeToFit()
}
Uncheck the "Preferred Width" explicit checkbox(In Size Inspector)
Remove the height constraint on you UILabel.
It will definitely work.

Unable to get the height of a UILabel with numberOfLines = 0

When I set a text to my label and check myLabel.frame.size.height I get always the same value, as if being always a single line, even if the text I set takes multiple lines... How could I get the "final" height?
Thanks
Try it inside your View Controller's viewDidLayoutSubviews function:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
print(myLabel.frame.size.height)
}
Your label won't have it's final size until then.

Resources