Default UIView subclasses

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

While I don't use them yet, if the XIB provides a value, I would like it to override the default. But if the XIB does not give a value, I would like to get the default.

In this case, I am thinking about the CGFloat value. While it can be set to 0.0, it is not useful by default, so checking the value of 0.0 in my code and replacing it with a better value is something I would rather avoid.

+2


source to share


2 answers


Inject 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 is only executed if the view is built in code. If the view comes from a nib file, it will be initialized with initWithCoder: which modifies the attributes to match those in the nib file. To deal with this case, you can override initWithCoder :, check if the default attribute is set, 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;
}

      

+6


source


If it is a native property, then the XIB should set it to zero.

Therefore, as @cduhn said, you can change it to:



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

      

+1


source







All Articles