I'm creating UIKit
objects programmatically, like UIButton
, UIView
, UILabels
, etc.
Sometimes, I need to use the same view with same properties multiple times.
Example:
If I need to create a border line around a textField
, I create an instance of UIView
:
let textFieldTopViewSeparator: UIView = {
let view = UIView()
view.backgroundColor = UIColor.gray
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
Then, set its constraints:
func textFieldTopViewSeparatorConstraints() {
textFieldTopViewSeparator.heightAnchor.constraint(equalToConstant: 1).isActive = true
textFieldTopViewSeparator.topAnchor.constraint(equalTo: self.textField.topAnchor).isActive = true
textFieldTopViewSeparator.widthAnchor.constraint(equalTo: self.textField.widthAnchor).isActive = true
textFieldTopViewSeparator.centerXAnchor.constraint(equalTo: self.textField.centerXAnchor).isActive = true
}
And call both in viewDidLoad()
:
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(textFieldTopViewSeparator)
textFieldTopViewSeparatorConstraints()
}
That's only will create a border at the top of the textField
, then to create a bottom one, I need to create another view, give it constraints, and call them again in viewDidLoad()
So my question is, is there a way to create only one instance of the view and use it multiple times with different constraints? Even with a different way to do create the view.