Search code examples
cocoasubclassing

UILabel subclass


I know that this is a newbie question but I am a newbie so here goes:

I wish to use Chalkduster font quite a lot throughout my app (buttons, labels etc) and have tried subclassing UILabel to achieve this. I have the following in Default.h:

#import <UIKit/UIKit.h>

@interface Default : UILabel
{
UILabel *theLabel;
}

@property (nonatomic, strong) IBOutlet UILabel *theLabel;

@end

and this in my .m:

#import "Default.h"

@implementation Default

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    // Initialization code


UIFont *custom = [[UIFont alloc] init];

custom = [UIFont fontWithName:@"Chalkduster" size:18];

self.font = custom;


NSLog(@"h");
}
return self;
}

@end

When I change the class in interface builder and run, I'm not seeing the Chalkduster font. I'd appreciate a hand in getting this set up as I believe it will save me a lot of time. Cheers.


Solution

  • Some problems to fix:

    1) You're mixing up the idea of Default being a label and Default containing a label. To subclass, get rid of the property inside your class and make your changes to self rather than theLabel (inside the if (self) { section).

    2) Anything you code after an unconditional return isn't going to get executed...and I'm surprised the compiler didn't complain about those statements.

    Edit: ...and one more thing that just dawned on me.

    3) If you're loading from a xib or storyboard, the initialization is done by initWithCoder: instead of initWithFrame:, so:

    - (id)initWithCoder:(NSCoder *)coder {
        self = [super initWithCoder:coder];
        if (self) {
            self.font = [UIFont fontWithName:@"Chalkduster" size:18];
        }
        return self;
    }