swift - Getting run time error when adding constraints -
i'm trying center image view i'm getting error..this code:
let markerimage = #imageliteral(resourcename: "ic_new_mark_icon") let size = cgsize(width: 60, height: 60) var newimage = imagewithimage(image: markerimage, scaledtosize: size) var imageview = uiimageview(image: newimage) self.view.addsubview(imageview) let xconstraint = nslayoutconstraint(item: imageview, attribute: .centerx, relatedby: .equal, toitem: self.view, attribute: .centerx, multiplier: 1, constant: 0) let yconstraint = nslayoutconstraint(item: imageview, attribute: .centery, relatedby: .equal, toitem: self.view, attribute: .centery, multiplier: 1, constant: 0) imageview.addconstraint(xconstraint) imageview.addconstraint(yconstraint)
and error is
2016-12-22 16:29:11.305417 googlemappractice[21426:362773] [layoutconstraints] view hierarchy not prepared constraint: <nslayoutconstraint:0x600000285f00 uiimageview:0x7ff772f15560.centerx == uiview:0x7ff772c0bd30.centerx (inactive)> when added view, constraint's items must descendants of view (or view itself). crash if constraint needs resolved before view hierarchy assembled. break on -[uiview(uiconstraintbasedlayout)
the constraints need added earliest common ancestor of 2 views affected constraint. in case, self.view
earlier in hierarchy constraints should added instead of imageview
.
since ios 8, there easier way. once you've added view view hierarchy (with addsubview
), can activate constraints instead of adding them views.
you can setting isactive
property true:
xconstraint.isactive = true yconstraint.isactive = true
or using activate
class function of nslayoutconstraint
active multiple constraints:
nslayoutconstraint.activate([xconstraint, yconstraint])
as mentioned @dfd in comments, should set flag:
imageview.translatesautoresizingmaskintoconstraints = false
this tells ios not create constraints imageview
based upon frame. if don't this, you'll end conflicting constraints.
you going need width , height constraints imageview
well, because you've specified position far.
Comments
Post a Comment