0

I need to set a property of a UIView before awakeFromNib is fired.

This is what I tried:

if let views = Bundle.main.loadNibNamed("MyNib", owner: self, options: nil) as? [MyNib], 
views.count > 0 {
let v = views.first!
v.count = 78
// or
v.configureContent(n: 78)
return v...

configureContent gets called but after awakeFromNib, so I can't use the value of count inside the body of awakeFromNib.

I red here about the options parameter, but I'm not sure it can be of any help.

Another option would be to avoid any sort of injection and ask for data from some source directly from the awakeFromNib.

Any help is appreciated.

  • 1
    `init(coder aDecoder: NSCoder)` gets called before `awakeFromNib()`, so what about there? – trojanfoe Feb 12 '19 at 09:57
  • ... also `didMoveToSuperview()` and some others... – trojanfoe Feb 12 '19 at 09:58
  • @trojanfoe: if I move all my code to `init` (previously unused), the code crashing when I set the delegate for a UIScrollView (`scrollView.delegate=self`) –  Feb 12 '19 at 10:09
  • Do it later (in the lifecycle) then, like `didMoveToSuperview()`. – trojanfoe Feb 12 '19 at 10:10
  • (anyway, if I print the value of count, it is 0, that's the default value, not the one I pass from outside) –  Feb 12 '19 at 10:12
  • @trojanfoe: in the context of my app, this could not be safe because the view is notified multiple times, even when I don't need the behavior contained in the `awakeFromNib` body. I can check if it has been removed (eg. `if let superview = self.superview {...)` but I can't imagine any other case when the superview changes (it is an MKAnnotationView) –  Feb 12 '19 at 11:21

0 Answers0