0

I am trying to understand how to properly used NSCoder when subclassing UIView:

required init?(coder aDecoder: NSCoder) {
  super.init(coder: aDecoder)
}

I am wondering whether it is possible to access any properties that aDecoder might carry. I would e.g. expect it to know the size of the frame that the view has in Storyboards. Is it possible to access this information? I tried the following but it only returned 0-values for the CGRect:

required init?(coder aDecoder: NSCoder) {
  let frame = aDecoder.decodeCGRect(forKey: "frame")
  print(frame) // prints: (0.0, 0.0, 0.0, 0.0)
  super.init(coder: aDecoder)
}

I checked the documentation of UIView, but there is no info on this.

nburk
  • 22,409
  • 18
  • 87
  • 132
  • It will probably change in the first layout pass. If you are using constraints, the frame won't be in the coder. Why do you need to know? What are you trying to accomplish? There's probably a different way of doing it. – i_am_jorf Oct 10 '16 at 23:46
  • just tried it after `super.init()` but it still only prints: `(0.0, 0.0, 0.0, 0.0)`. shouldn't `aDecoder` carry the basic info about the view's setup in storyboards? like `frame` or `backgroundColor` so that it can be used in `UIView`'s initializer? – nburk Oct 10 '16 at 23:47
  • 99% of the time the frame of an object in a storyboard will be set by constraints, not a frame specified in the storyboard. `backgroundColor` is different; this is a property that would typically be set explicitly in the storyboard and should be available after the call to `super.init`. Normally your subclass will specify, via `intrinsicContentSize` the size that it wants to be – Paulw11 Oct 10 '16 at 23:58

1 Answers1

-1

If you need actual dimensions of your custom-view, then you should look at your view's view-controller method:

-(void) viewDidLayoutSubviews

Your custom view should have it's proper dimensions set when this gets called.

cbiggin
  • 1,942
  • 1
  • 17
  • 18