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")!))
2
Answers
U need to add subview first, then activate layout. Label is not in myView subviews in your code. It is not in any hierarchy at the moment of layout constraint activation.
You need to configure the layout of your subviews (
imageView
andlabel
) in order to have them sized and positioned where you want them.Take a look at this example code:
I modified your
getMarker(...)
func to size and position the subviews.I also added a very similar
getMarkerAutoSized(...)
func that uses a couple additional constraints on the subviews.For the first version, we must set both the Position and Size of the generated view.
For the second version, we only need to set the generated view’s Position because it sizes itself to fit its subviews.
Here’s how they look: