1

I know how to get the distance between two points in swift. But I want to know how to get the distance between two anchors as a CGFloat.

For example: I want to find the distance between the

view.topAnchor

and the

button.topAnchor

on a view controller like this: enter image description here

I'm guessing I will have to get a CGPoint of the anchors (then I can just find the difference between the y points of the CGPoint's). I just don't know how to do that.

Slaknation
  • 2,124
  • 3
  • 23
  • 42

1 Answers1

3

Anchors are actually there to construct constraints. If you are already using them you can get the value just by using constraint.constant property. Like This,

let view = UIView()
let button = UIButton()
view.addSubview(button)

let heightConstraint = button.topAnchor.constraint(equalTo: view.topAnchor)
heightConstraint.isActive = true
view.layoutIfNeeded() // update incase still not updated
print(heightConstraint.constant)

But I think what you actually trying to achieve is,

let distance = button.frame.minY - view.frame.minY

measuring the distance like this.

Shreeram Bhat
  • 2,849
  • 2
  • 11
  • 19