So I started to learn Programmatic UI after I struggled with Storyboard.
I basically figured out where can I store the View's code such as button, textfield, etc.
But my problem is I don't want to see all the constraints below in my VC.
Is there any way to store all these constraints somewhere or coding some function to call them every time I want to add constraints?
I know it is gonna be longer when I add more components...
For example;
func configureTextField() {
self.view.addSubview(usernameTextField)
NSLayoutConstraint.activate([
self.usernameTextField.topAnchor.constraint(equalTo: self.logoImageView.bottomAnchor, constant: 20),
self.usernameTextField.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 40),
self.usernameTextField.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -40),
self.usernameTextField.heightAnchor.constraint(equalToConstant: 50)
])
}
CodePudding user response:
It seems to me that you're just complaining that autolayout constraint code is verbose. And you know what? You're right! It is verbose. It's not as verbose as it used to be, but it's still verbose.
There are three solutions that programmers use:
Make use of stack views. When views line up horizontally or vertically, you can use a single stack view to arrange them. A stack view is a view that creates constraints. Thus, you don't have to create those constraints yourself (though you do have to create, configure, and constrain the stack view).
Write convenience methods. For example, our team has methods like
addConstrained(subview:top:left:bottom:right:)
. We still have to write a boatload of constraint code but it's a lot simpler and shorter than writing it all out one anchor at a time as you are doing.Use a library. Basically this is just a pre-existing collection of convenience methods. For example, many people like SnapKit (though personally the last thing I want in my code is yet another layer of dependency, so I don't use it myself).