user1945317
user1945317

Reputation: 107

How to override Objective-c class functions in Swift?

I'm currently trying to override the systemFontOfSize method of UIFont to return my custom font with the given font size. My code currently looks like this:

extension UIFont
{
    class func systemFontOfSize(fontSize: CGFloat) -> UIFont
    {
        return UIFont(name: "HelveticaNeue", size: 10)!
    }
}

However, I am unable to override that method. When using the code shown above, I get the following error:

"Method 'systemFontOfSize' with Objective-C selector 'systemFontOfSize:' conflicts with previous declaration with the same Objective-C selector"

When adding override, the error is that the method is not overriding anything. Does anyone know how to fix this issue?

Upvotes: 0

Views: 2142

Answers (5)

Tanya Berezovsky
Tanya Berezovsky

Reputation: 91

You can use the #selector to redirect UIFont calls go to custom functions.

For best way how to replace font functions for whole iOS app, please check the below SO question, look for answer from - Javier Amor Penas:

Set a default font for whole iOS app?

Upvotes: 1

Michi
Michi

Reputation: 1484

You can use Objective C extension as follows, if it fits your needs.

Earlier discussion related to this technique with my source code as an answer can be found here: Is there a way to change default font for your application.

All you have to do is to implement the class with the code mentioned at the link above and include the following header file in your umbrella header to be able to make the code be applied when calling methods in Swift code.

Header file UIFont+Utils.h:

@interface UIFont (Utils)

+ (UIFont *)systemFontOfSize:(CGFloat)size;
+ (UIFont *)lightSystemFontOfSize:(CGFloat)size;
+ (UIFont *)boldSystemFontOfSize:(CGFloat)size;
+ (UIFont *)preferredFontForTextStyle:(NSString *)style;

@end

Upvotes: 1

user3441734
user3441734

Reputation: 17534

to be able to override the function, you must first subclass UIFont. what are you trying to do, is impossible. you are trying to redefine function in extension. so, i have no positive message, but that is the reality.

PS: if you are an Objective C 'expert', some hack could be available ...

Upvotes: 0

Cristik
Cristik

Reputation: 32786

From Apple's documentation on extensions:

NOTE

Extensions can add new functionality to a type, but they cannot override existing functionality.

You cannot overwrite existing methods in an extension, you can only add new ones.

Upvotes: 0

Shebing Yang
Shebing Yang

Reputation: 66

class FontClass: UIFont{ override class func systemFontOfSize(fontSize: CGFloat) -> UIFont { return UIFont(name: "HelveticaNeue", size: 10)! } } In the project, you can use it like this: FontClass.systemFontOfSize(10) The hope can help you!

Upvotes: 0

Related Questions