netdigger
netdigger

Reputation: 3789

Why doesnt my UILabel change font?

I've read different answers here about custom fonts in XCode, but I still cant get it to work.

What I've done:

Added it to Plist. Added it to Copy boundle resources.

If I do:

for ( NSString *familyName in [UIFont familyNames] )
    {
        NSLog(@"Family: %@", familyName);
        NSLog(@"Names = %@", [UIFont fontNamesForFamilyName:familyName]);
    }

It will print it:

2013-03-26 17:04:52:214 Appname[21704:2311] Family: Patrick Hand
2013-03-26 17:04:52:217 Appname[21704:2311] Names = (
    "PatrickHand-Regular"
)

And I've tried to set the font with both:

self.usernameLabel.font = [UIFont fontWithName:@"PatrickHand-Regular" size:30];

and

self.usernameLabel.font = [UIFont fontWithName:@"PatrickHand" size:30];

My most desperate attempt was this:

for ( NSString *familyName in [UIFont familyNames] )
    {
        NSLog(@"Family: %@", familyName);
        NSLog(@"Names = %@", [UIFont fontNamesForFamilyName:familyName]);
        [self.usernameLabel setFont:[[UIFont fontNamesForFamilyName:familyName] objectAtIndex:0]];
        if ( [familyName isEqualToString:@"Patrick Hand" ])
        {
        NSLog(@"BREAK!");
        break;
        }
    }

But it still doesn't change.

Suggestions what to try?

Upvotes: 1

Views: 832

Answers (1)

NSGod
NSGod

Reputation: 22948

When you want to change something in the user interface by using an IBOutlet instance variable, you need to make sure you call the code at the appropriate time.

For example, let's say you have a class like the following:

@interface MDViewController : UIViewController

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

@end

There is also an MDViewController.nib file which holds the UI of the view controller, and let's say you want to set the contents of the label to some value.

Normally, init methods like init or initWithCoder: are called too early in the lifetime of the object to be able to communicate with the objects in the UI, as the nib file has not yet been fully loaded, and your IBOutlet instance variables at that point will still be nil.

Later on, in methods like awakeFromNib, viewDidLoad, viewWillAppear, and viewDidAppear, the IBOutlets will be properly set up and you can communicate with the UI objects.

In your case, viewDidLoad or viewWillAppear are probably good points to set this value (which one depends on your specific needs).

Upvotes: 1

Related Questions