I get a surprising crash when adapting constraints.
- Xcode 13.2.1
- iOS 15.2 on simulator
Here is the set up in storyboard:
A subclass of UIView (PopoverView) to draw a popover like frame and label and button inside.
PopoverView can set its arrow position all around, for instance on the right, so that popover will appear on the left of an object,
or on the left, to appear on the right.
Button tap is used to loop through the arrow position.
I have defined constraints (and their IBOutlets), and notably for the centerX position of popoverView to centerX of the label.
I adapt the value of the constraints in viewWillLayoutSubviews to position the popover in correct position relative to the label.
Now the problem.
To position the popover on the right of the label, I set its centerX
constraint as follows in viewWillLayoutSubviews():
popoverCenterToLabelCenterConstraint.constant = (popoverLabel.frame.width + label.frame.width) / 2
That works OK
To position the popover on the left of the label, I set its constraint as follows (offset the opposite value):
popoverCenterToLabelCenterConstraint.constant = -(popoverLabel.frame.width + label.frame.width) / 2
I also tried:
popoverCenterToLabelCenterConstraint.constant = -popoverLabel.frame.width / 2 - label.frame.width / 2
App does not crash but hangs, apparently in an infinite loop. Idem if I divide by 2.0 instead of 2 : label.frame.width / 2.0
The width of the label, at this point of code, is 92.33333333333333
So I replaced by the value directly:
popoverCenterToLabelCenterConstraint.constant = -popoverLabel.frame.width / 2 - 46.2
and it works OK. Idem with 46.1 So the problem is not due to the position of popoverView
If I replace the div by 2 by 2.01 :
- popoverCenterToLabelCenterConstraint.constant = -popoverLabel.frame.width / 2 - label.frame.width / 2.01
it works !!!!!!
Conclusion: it is the exact div by 2 that causes the hanging.
What could be the reason for this strange behaviour ?