Reputation: 107
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
Reputation: 91
You can use the #selector
to redirect UIFont
calls go to custom functions.
Upvotes: 1
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
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
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
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