5

I want define a macro for unifying all fonts in my app:

#define EXO_REGULAR_FONT(size) [UIFont fontWithName:@"Exo-Regular" size:size]

and than using this macro like this:

myLabel.font = EXO_REGULAR_FONT(15);

But the compiler give me this error:

enter image description here

(there is an arrow under 15).

Any ideas to resolve ? Thanks

4 Answers 4

13

Change the name of your parameter:

#define EXO_REGULAR_FONT(theFontSize) [UIFont fontWithName:@"Exo-Regular" size:theFontSize]

From GCC manual:

When the macro is expanded, each use of a parameter in its body is replaced by the tokens of the corresponding argument

So when your macro is expanded, it inserts this in your code, hence the compilation error:

[UIFont fontWithName:@"Exo-Regular" 15:15]
2
  • what is possible solution for swift-4 ? Jun 20, 2018 at 10:55
  • @Anita see Nikolai's answer bellow and the its comments. A good way to do this in Swift would be to add it as an extension to UIFont. Jun 20, 2018 at 12:35
5
#define EXO_REGULAR_FONT(size) [UIFont fontWithName:@"Exo-Regular" size:size]

gets expanded, when you call EXO_REGULAR_FONT(15), to

[UIFont fontWithName:@"Exo-Regular" 15:15]

So you need to define it like this for example:

#define EXO_REGULAR_FONT(_size_) [UIFont fontWithName:@"Exo-Regular" size:_size_]
5

Don't use a macro; they are evil (you did just experience one of the many reasons).

Use a function instead:

static inline UIFont *ExoRegularFont(CGFloat size) {
   return [UIFont fontWithName:@"Exo-Regular" size:size];
}
4
  • Would be bad practice to keep this in something similar to macros.h and attach it in your pch?
    – BooRanger
    Jul 2, 2013 at 10:15
  • @BooRanger Not at all. Definitely much better and safer than the #define. Jul 2, 2013 at 11:07
  • 1
    a category on UIFont would also be a good way to handle custom fonts. Similar to +systemFontOfSize: I use +appFontOfSize:, +boldAppFontOfSize:, +headingFont, ... in my apps. Jul 2, 2013 at 11:33
  • 1
    @MatthiasBauch You should add this comment as a new answer. Jul 2, 2013 at 14:37
3
#define EXO_REGULAR_FONT(s) [UIFont fontWithName:@"Exo-Regular" size:s]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.