Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define macro for UIFont doesn't work

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

like image 558
Fry Avatar asked Jun 27 '13 09:06

Fry


3 Answers

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]
like image 198
Guillaume Algis Avatar answered Oct 10 '22 09:10

Guillaume Algis


#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_]
like image 34
Cyrille Avatar answered Oct 10 '22 08:10

Cyrille


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];
}
like image 28
Nikolai Ruhe Avatar answered Oct 10 '22 08:10

Nikolai Ruhe