Search code examples
iosswiftuistoryboarduicontrol

Custom UIControl (slider) does not abide by constraints until interacted with


I followed this tutorial to build a custom slider that subclasses UIControl. It works great when the control is programmatically inserted into the view, with the exact size, position, etc.

However, I wanted to use Storyboard to visually align the components of my view, so I added @IBDesignable and @IBInspectable to the custom slider class. Here's my problem:

  1. In the Storyboard, I added the custom slider and added constraints for "Trailing Space to superview" and "Leading Space to superview".
  2. However, when I run it on my device, initially it doesn't respect the constraints set above, until I interact with the slider (touch the button) and suddenly the constraints are enforced.
  3. I tried to call setNeedsDisplay in the init (coder: NSCoder) method, but nothing works.

Does anyone have any idea why this is happening and how I can fix it?


Solution

  • Calling setNeedsDisplay in init is obviously too early. Try viewWillAppear and also try calling layoutSubviews on the controller's view.

    But of course, the underlying error is a misconfiguration in the storyboard. (That would be difficult to debug via this platform).