I want to programmatically set the constraints for the view. I'm using the code from Apple's Swift library:
Creating layout anchors
// Get the superview's layout
let margins = view.layoutMarginsGuide
// Pin the leading edge of myView to the margin's leading edge
myView.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true
But my code doesn't work.
import UIKit
class ViewController: UIViewController {
var myView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
myView.frame.size.width = 100
myView.frame.size.height = 100
myView.backgroundColor = .green
view.addSubview(myView)
let margins = view.layoutMarginsGuide
myView.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
}
}
I am not getting any error messages. But my view always stays in the same place, in the upper left corner. Even if I change the constraint to center or bottom, the view doesn't move.
Could you tell me what is wrong in my code?