In this article we will learn about the difference between leading and left, trailing and right constraints in Swift.
In short, by setting the leading constraint we set the starting point of a view, while the trailing constraint sets the ending point. If we are using English language in our app, leading and left anchors are the same thing, just like the trailing and right ones. But if we add support for RTL (Right-to-left) languages like Arabic, Hebrew, or Urdu, leading will mean _right, _and trailing willmean left.
Now let’s explore this difference on a simple example.
Our ViewController
has a rounded UIView
containing a UILabel
:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(roundedView)
roundedView.addSubview(titleLabel)
}
let roundedView: UIView = {
let view = UIView()
view.layer.cornerRadius = 20
view.backgroundColor = .systemBlue
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let titleLabel: UILabel = {
let label = UILabel()
label.textColor = .white
label.text = NSLocalizedString("Hello", comment: "")
label.font = .systemFont(ofSize: 20)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
}
Note that the titleLabel
displays a localized string. Let’s now add some constraints for both the roundedView
and titleLabel
inside the viewDidLoad()
method:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
...
NSLayoutConstraint.activate([
roundedView.widthAnchor
.constraint(equalTo: view.widthAnchor,
multiplier: 0.8),
roundedView.heightAnchor
.constraint(equalTo: view.heightAnchor,
multiplier: 0.3),
roundedView.centerXAnchor
.constraint(equalTo: view.centerXAnchor),
roundedView.centerYAnchor
.constraint(equalTo: view.centerYAnchor),
])
NSLayoutConstraint.activate([
titleLabel.leftAnchor
.constraint(equalTo: roundedView.leftAnchor,
constant: 20),
titleLabel.topAnchor
.constraint(equalTo: roundedView.topAnchor,
constant: 10)
])
}
...
}
#programming #xcode #swift #mobile #ios