UILabel subclass

ε祈祈猫儿з 提交于 2020-01-03 06:33:08

问题


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.


回答1:


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;
}



回答2:


First of all I don't think that You're subclassing UILabel correctlly. So I made tutorial for You explaining how to do it. You don't need to IBOutlet object which is subclassed. JUST CALL IT WITH SELF. for example: self.font = ... If You want to subclass UILabel do this:

Create new class with title myLabel like this:

.h

#import <UIKit/UIKit.h>

@interface MyLabel : UILabel {

}

@end

.m

#import "MyLabel.h"

@implementation MyLabel

-(void)awakeFromNib {

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

    self.font = custom;
}

@end

Now select Your label in storyboard and go to indentity inspector and in Custom Class select created class above. Like this:

Output:

Note: Don't forget to release custom because You are allocating it.




回答3:


Move the return self; three lines down. You return from the init method before you do your custom initialization.

Edit to reflect new information from comment:

When deserializing the view from a nib you also have to override initWithCoder:



来源:https://stackoverflow.com/questions/11190927/uilabel-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!