Reputation: 138
As the title suggests, i struggle to find a way to calculate the vertical distance between UIViews. Say i have two buttons in a View Controller. How would I go about getting a CGFloat indicative of the distance between button1's bottom and button2's top?
Upvotes: 2
Views: 2426
Reputation: 1984
As already pointed out by @lobstah, the difference can be calculated by accessing the frames of the views in question.
However, there's an important detail that must be considered: This only works in that simple way, if the views share the same parent view. Because only then, the frames will be expressed with regards to the same coordinate space.
A general approach with doesn't come with this restriction and will always work as long as the views are part of the same view hierarchy (don't appear on different windows) and are not scaled / rotated by an affine transform is the following:
func distanceBetween(bottomOf view1: UIView, andTopOf view2: UIView) -> CGFloat {
let frame2 = view1.convert(view2.bounds, from: view2)
return frame2.minY - view1.bounds.maxY
}
The distance would be positive if the top of view2 is below the bottom of view1.
Upvotes: 5
Reputation: 881
You can use maxY of the top and minY of bottom view’s frames properties:
bottomView.frame.minY - topView.frame.maxY
Upvotes: 1