Question

Im extending the UIButton Class to be able to set the font and color of the UINavigationBarButton ( from this code example: switch on the code )

I goes like this:

@interface NavBarButtonGrey : UIButton 
-(id)init;

@end


@implementation NavBarButtonGrey

-(id)init {
if(self = [super init]) {
    self.frame = CGRectMake(0, 0, 49.0, 30.0);
    self.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    self.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

    UIImage *image = [UIImage imageNamed:@"greyNavButton.png"];
    UIImage *stretchImage = 
    [image stretchableImageWithLeftCapWidth:15.0 topCapHeight:0.0];
    [self setBackgroundImage:stretchImage forState:UIControlStateNormal];
    self.backgroundColor = [UIColor clearColor];
    [self setTitleShadowColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.titleShadowOffset = CGSizeMake(0, -1);
    self.titleLabel.font = [UIFont boldSystemFontOfSize:13];
}

return self;
}
@end

This is ok, but of course not very flexible. How do I incorporate using a typedef enum (like Apple does) for all the different colors, fonts and sizes I would like my custom button to conform to.

The only thing I can get out of the interface files from UIKit is that it is done like this:

typedef enum {
RGCustomNavBarButtonStyleBlue,
RGCustomNavBarButtonStyleGrey,
RGCustomNavBarButtonStyleBlack,
RGCustomNavBarButtonStyleGreen,
RGCustomNavBarButtonStyleRed, 
} RGCustomNavBarButtonStyle;

How to get from that and into a working implementation that takes font, size, color etc. from the values of the enum through the constructor(initWithStyle)?

Does one overload constructors in Objective C? multiple constructors?

Hope it makes sense and thank you for any help given:)

Was it helpful?

Solution

You can have multiple constructors such as;

-(MyClass) initWithFont: (UIFont) font;
-(MyClass) initWithFonmt: (UIFont) font andColor: (UIColor) color;

etc.

Then call [super init] as the first line in each of your custom constructors.

OTHER TIPS

To expand on what ennuikiller said above, I was taught (Hillegass's book) to pick one initializer—usually the one with the most options, like your initWithFont:andColor:—and have the other initializers call it. That main initializer is referred to as the designated initializer.

So your code would have a fully-implemented initWithFont:andColor: that calls [super init], and then you'd also have an initWithFont: that looks something like this:

-(MyClass) initWithFont: (UIFont) font
{
    [self initWithFont:font andColor:RGCustomNavBarButtonStyleBlack];
}

Then your initWithFont:andColor: would handle all the other setup and calling [super init].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top