I want to set label & Imageview in centre of myView but App crashing after adding some constraints

Error:- Thread 1: "Unable to activate constraint with anchors <NSLayoutXAxisAnchor:0x280af8500 \"UILabel:0x103dc4fa0.centerX\"> and <NSLayoutXAxisAnchor:0x280af89c0 \"UIView:0x103dc49d0.centerX\"> because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal."

I've created a function programmatical in Base view controller which returns a view & I've added some constraints to its

Function:-

func getMarker (lbl:String, img:UIImage) -> UIView {
        let myView = UIView(frame: CGRect.zero)
        myView.center = CGPoint(x: 50, y: 160)
        myView.backgroundColor = UIColor.clear


        let imageView = UIImageView(image: img)
        imageView.frame = CGRect(x: 0, y: 0, width: 20, height: 40)
        myView.addSubview(imageView)


        let label = UILabel(frame: CGRect(x: 0, y: 45, width: 120, height: 30))
        label.text = lbl
        label.textAlignment = .center
        label.adjustsFontSizeToFitWidth = true
        label.textColor = UIColor.black
        label.backgroundColor = UIColor.white
        label.layer.borderColor = UIColor.lightGray.cgColor
        label.layer.borderWidth = 0.5
        label.layer.cornerRadius = 5
        label.layer.masksToBounds = true
        label.sizeToFit()

        NSLayoutConstraint.activate([
            label.centerXAnchor.constraint(equalTo: myView.centerXAnchor),
            imageView.centerXAnchor.constraint(equalTo: myView.centerXAnchor)
        ])

        myView.addSubview(label)

        return myView
    }

calling function in another controller but it crashing and showing me the error which I mentioned above

Calling function:-

getMarker(lbl: device.name ?? "", img: (UIImage(named: icfile) ?? UIImage(named: "truck_1_orange")!))

You should add label as subview before creating constraint.

myView.addSubview(label)

Add subview before setting the constraint.

        myView.addSubview(label)

        NSLayoutConstraint.activate([
            label.centerXAnchor.constraint(equalTo: myView.centerXAnchor),
            imageView.centerXAnchor.constraint(equalTo: myView.centerXAnchor)
        ])

 I want to set label and imageView in the center of myView,

centerX renters horizontally.

Do you want to center vertically as well, to get really at center ?

If so, complete it as:

        NSLayoutConstraint.activate([
            label.centerXAnchor.constraint(equalTo: myView.centerXAnchor),
            label.centerYAnchor.constraint(equalTo: myView.centerYAnchor),

            imageView.centerXAnchor.constraint(equalTo: myView.centerXAnchor)
            imageView.centerYAnchor.constraint(equalTo: myView.centerYAnchor)
        ])
I want to set label & Imageview in centre of myView but App crashing after adding some constraints
 
 
Q