I am learning about layout constraints and find it a bit confusing why the last line of NSLayout Constraints for the trailing anchor mentions a view instead of loginView? Is there any good logical way to think of this? Struggling to imagine what is written.
let loginView = LoginView()
view.addSubview(loginView)
NSLayoutConstraint.activate([
loginView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
loginView.leadingAnchor.constraint(equalToSystemSpacingAfter: view.leadingAnchor, multiplier: 1),
view.trailingAnchor.constraint(equalToSystemSpacingAfter: loginView.trailingAnchor, multiplier: 1)
])
CodePudding user response:
The code you posted is defining a set of layout constraints for the loginView object. The constraints specify how the loginView
should be positioned within its parent view.
In the last line of the code, the view.trailingAnchor
is being used as the reference for the trailing edge of the loginView
. This means that the loginView
will be positioned such that its trailing edge is aligned with the trailing edge of the parent view.
In general, when working with layout constraints, it is important to think about the relationship between the views being constrained and the constraints themselves. In this case, the loginView
is the view being constrained, and the constraints are defining how the loginView
should be positioned relative to its parent view.
CodePudding user response:
view
means self.view
. This is a UIViewController; it has a view. This is the view that will contain the loginView
; you can actually see the loginView
being added to the view controller's view as a subview, right there in the code.
So this code inserts the loginView
into self.view
and then proceeds to describe the physical relationship between their sizes and positions.