leftAnchor 和 leadingAnchor 的区别?

Difference between leftAnchor and leadingAnchor?

我一直在为 iOS 使用 Swift 中的约束,并且大多数命名 conventions/documentation 使事情变得不言自明,但最近让我感到困惑的一件事是两个成对的 NSLayoutXAxisAnchor class:

leadingAnchor, leftAnchor

以及

trailingAnchor, rightAnchor

当我在我的 iOS 应用程序中以编程方式设置约束时,我发现我可以完全互换地使用这些约束。如果我使用 leadingAnchor,运行 应用程序并观察行为,然后使用 leftAnchor,运行 应用程序并观察行为,它的功能完全相同。

我查看了developer.apple.com的文档,结果竟然完全一样(忽略名字的不同)。例如比较 leadingAnchor 和 leftAnchor:

"Use this anchor to create constraints with the view’s leading edge. You can only combine this anchor with a subset of the NSLayoutXAxisAnchor anchors. You can combine a leadingAnchor with another leadingAnchor, a trailingAnchor, or a centerXAnchor. For more information, see NSLayoutAnchor Class Reference."

比较:

"Use this anchor to create constraints with the view’s left edge. You can only combine this anchor with a subset of the NSLayoutXAxisAnchor anchors. You can combine a leftAnchor with another leftAnchor, a rightAnchor, or a centerXAnchor. For more information, see NSLayoutAnchor Class Reference."

有谁知道这些属性之间是否有任何预期的区别?

WWDC 2015 的一个视频中Autolayout 的奥秘 中(我认为这是第 1 部分,但都值得一看)对此进行了(简要)介绍。

Left 和 Right 约束是绝对的,它们将始终引用屏幕或控件的 left/right。前导和尾随约束受设备区域设置的影响;在阅读方向是从左到右的语言环境中(英语、法语、西班牙语等),前导和左(以及尾随和右)可以互换使用。在阅读方向是从右到左的语言环境中(例如希伯来语、阿拉伯语),那么 'leading' 将是右侧,而 'trailing' 将是左侧。

视频中的建议是您几乎应该始终使用 leading/trailing 而不是 left/right,除非您对绝对 left/right 有特定要求。

考虑标签和文本字段的典型 'form'。如果您使用 leading/trailing 约束,那么对于英语语言环境,您将在左侧获得标签,在右侧获得文本字段,对于希伯来语语言环境,在右侧获得标签,在左侧获得文本字段。

如果您制作了一款儿童应用程序,您从左到右进行教学,并且您总是想要屏幕左侧的 'left' 按钮,那么 left/right 约束是适当的