Constraints don't work (UIKit)

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

Link

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?

before adding a constraint you must set the translatesAutoresizingMaskIntoConstraints=false on the given view.

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
        /**
         set translatesAutoresizingMaskIntoConstraints=false for every view a constraint is being applied to*/
        myView.translatesAutoresizingMaskIntoConstraints=false 
        myView.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
    }
}

Unless you set translatesAutoresizingMaskIntoConstraints to false, your view’s frame, bounds, and center properties, and its autoresizing mask, will generate implicit constraints that pin your view in place. See the documentation for details.

Set translatesAutoresizingMaskIntoConstraints to false, and add constraints as needed to compute your view’s size and position instead.

I have added the

myView.translatesAutoresizingMaskIntoConstraints = false

code line to my code.

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)


        myView.translatesAutoresizingMaskIntoConstraints = false

        let margins = view.layoutMarginsGuide

        myView.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
    }
}

But now. i get a blank screen.

Why is this happening?

Constraints don't work (UIKit)
 
 
Q