Leading, Trailing vs Left, Right Constraints

Ahmed
3 min readDec 4, 2021

--

The image above evidently expresses the same emotion when we see leadingAnchor and leftAnchor. After spending some time on Xcode and obviously on google, I found a clear and most important difference between leading, trailing, and left, right anchor. This concept is really useful in localization when you are dealing with languages such as Arabic because it is a right to left language.

Left and Right constraints

Left and Right constraints are absolute, they will always refer to the left/right of the screen or the control, both are strongly fixed and always depend on the left and right sides of the screen.

Leading and Trailing constraints

Leading and trailing constraints are affected by the device locale; In locales where the reading direction is left to right (English, French, Spanish, and so on) leading & left (and trailing & right) can be used interchangeably. In locales where the reading direction is right to left (e.g Hebrew, Arabic) then ‘leading’ will be the right side, and ‘trailing’ will be the left side.

When to use Left and Right constraints?

While using localization, Apple automatically does numerous stuff. For example, if you are localizing your app in English and Arabic, it will automatically change the leading to right and trailing to left. Contrary, if you want your constraint to remain the same way in the case of both English and Arabic, you would use the leftAnchor and rightAnchor instead of leading and trailing.

class ViewController: UIViewController {

override func viewDidLoad() {

super.viewDidLoad()

NSLayoutConstraint.activate([

titleLabel.leadingAnchor .constraint(equalTo: roundedView.leadingAnchor, constant: 20),]) }

}

constraints using the leading anchor (English)
constraints using the leading anchor (Arabic)

Noticed, how Xcode automatically has automatically changed the alignment of a text. The above snippets visually explain how leading changes its alignment to the right when the app is localized to Arabic.

Now we are using leftAnchor instead of leading.

class ViewController: UIViewController {

override func viewDidLoad() {

super.viewDidLoad()

NSLayoutConstraint.activate([

titleLabel.leadingAnchor .constraint(equalTo: roundedView.leftAnchor, constant: 20),]) }

}

constraints using the Left anchor (English)
constraints using the Left anchor (English)

Yeah yeah, I know that you get a point that using leftAnchor constraint didn't let the Xcode to change the alignment automatically.

I hope you found this useful. Thanks for reading!

--

--