IBInspectable property doesn't have its value in initWithCoder: initializer
Asked Answered
I

1

6

I am having this in MyClass.h file:

#import <UIKit/UIKit.h>

IB_DESIGNABLE

@interface MyClass : UIView

@end

and this is the code from the .m file:

-(void)awakeFromNib{
    [super awakeFromNib];

    NSLog(@"This works %lud",(unsigned long)self.max);
}

-(instancetype)initWithCoder:(NSCoder *)aDecoder{

    if ((self = [super initWithCoder:aDecoder])){

        NSLog(@"This doesn't work %lud",(unsigned long)self.max);
    }

    return self;
}

In awakeFromNib method, I get a correct value set in IB. In initWithCoder: I get this value equal to zero.

What is the appropriate time to check for a value, set in IB, for this property?

This is how I have defined a property in .m file:

@interface MyClass()

@property (nonatomic) IBInspectable NSUInteger max;

@end
Inescutcheon answered 11/12, 2016 at 16:3 Comment(0)
A
7

You seem to have answered your own question: awakeFromNib instead of initWithCoder:. awakeFromNib is later, and by that time, the runtime attributes have been set.

In real life, of course, you probably wouldn't care about this value until we get to viewDidLoad, which is considerably later than both.

Aiden answered 11/12, 2016 at 16:40 Comment(2)
Thanks. Well, I haven't really figured out yet what would be the most convenient way of using my class, but the idea was this: 1) Drag a view to a storyboard (and set its custom class to MyClass), 2) Enter values of inspectable properties. Also based on these properties I generate some additional content in my custom view (it is not everything visual defined in IB). So, at initialization of my view, I need values of those properties defined in IB. If you have any suggestions or hints about this flow, I am all ears. :)Inescutcheon
My answer remains the same. Do it in awakeFromNib, as you already deduced. But what I would do is wait until the view controller gets viewDidLoad. This is after the view has been created but before it is put into the interface. The view controller presumably has a reference to this view so it could tell it to finish configuring itself.Aiden

© 2022 - 2025 — McMap. All rights reserved.