【问题标题】:How to get the distance between two anchors?如何获得两个锚点之间的距离?
【发布时间】:2020-01-12 10:06:53
【问题描述】:

我知道how to get the distance between two points in swift。但我想知道如何将两个锚点之间的距离作为 CGFloat。

例如:我要查找两者之间的距离

view.topAnchor

button.topAnchor

在这样的视图控制器上:

我猜我必须得到一个锚点的 CGPoint(然后我可以找到 CGPoint 的 y 点之间的差异)。我只是不知道该怎么做。

【问题讨论】:

    标签: swift uiview uiviewcontroller layout-anchor


    【解决方案1】:

    锚点实际上是用来构造约束的。如果您已经在使用它们,则只需使用 constraint.constant 属性即可获取值。像这样,

    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)
    

    但我认为你真正想要实现的是,

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

    这样测量距离。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-08
      • 2019-07-26
      • 2014-02-17
      • 2020-03-22
      • 1970-01-01
      • 2020-06-01
      相关资源
      最近更新 更多