I'm working on Swift Playground right now. I declared UI objects in loadView()
in this case, Everything works fine.
But I tried to declare those labels outside of loadView() like this:
When I run this code (which labels are declared outside of loadView()), Constraints are not working except for width/height constraints.
Also, when i run the code only with 1 label, Everything works fine even label is declared outside of loadView()
Is there any solution to fix this problem?
Code Block Swift class ViewController: UIViewController { override func loadView() { let view = UIView(frame: viewRect) view.backgroundColor = UIColor.white let titleLabel = UILabel() titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.text = "title" titleLabel.backgroundColor = .gray view.addSubview(titleLabel) NSLayoutConstraint.activate([ titleLabel.widthAnchor.constraint(equalToConstant: 200), titleLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 100), titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor) ]) let subLabel = UILabel() subLabel.translatesAutoresizingMaskIntoConstraints = false subLabel.text = "title" subLabel.backgroundColor = .red view.addSubview(subLabel) NSLayoutConstraint.activate([ subLabel.widthAnchor.constraint(equalToConstant: 100), subLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 100), subLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor) ]) self.view = view } }
in this case, Everything works fine.
But I tried to declare those labels outside of loadView() like this:
Code Block Swift class ViewController: UIViewController { var titleLabel = UILabel() var subLabel = UILabel() override func loadView() { let view = UIView(frame: viewRect) view.backgroundColor = UIColor.white titleLabel = UILabel() titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.text = "title" titleLabel.backgroundColor = .gray view.addSubview(titleLabel) NSLayoutConstraint.activate([ titleLabel.widthAnchor.constraint(equalToConstant: 200), titleLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 100), titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor) ]) subLabel.translatesAutoresizingMaskIntoConstraints = false subLabel.text = "title" subLabel.backgroundColor = .red view.addSubview(subLabel) NSLayoutConstraint.activate([ subLabel.widthAnchor.constraint(equalToConstant: 100), subLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 100), subLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor) ]) self.view = view } }
When I run this code (which labels are declared outside of loadView()), Constraints are not working except for width/height constraints.
Also, when i run the code only with 1 label, Everything works fine even label is declared outside of loadView()
Is there any solution to fix this problem?