views:

374

answers:

2

What's the proper way to set a default value for a UIView subclass's property?

Although I'm not using them yet, if the XIB provides a value I'd like it to override the default. But if the XIB doesn't provide a value, I'd like my default value.

In this case, I'm thinking of a CGFloat value specifically. While it could be set to 0.0 this isn't a useful default, so checking for a value of 0.0 in my code and replacing it with a better value is something I'd rather avoid.

+5  A: 

Implement initWithFrame: in your subclass and set the property there.

- (id)initWithFrame:(CGRect)aRect {
    if (self = [super initWithFrame:aRect]) {
        // Set whatever properties you want.  For example...
        self.alpha = 0.75;
    }
    return self;
}

This designated initializer only executes if the view is constructed in code. If the view comes from a nib file, it will get initialized using initWithCoder:, which modifies the attributes to match the attributes in the nib file. To handle this case you can override initWithCoder:, test to see if the attribute is set to its default value, and if so, change it:

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super initWithCoder:decoder]) {
        if (self.alpha == 1.0) {
            self.alpha = 0.20;
        }
    }
    return self;
}
cduhn
+1  A: 

If it's your own custom property then the XIB should be setting it to zero.

Therefore, as @cduhn said, you can modify it in:

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super initWithCoder:decoder]) {
        lineWidth = 12; // whatever value you want
    }
    return self;
}
mahboudz