0

I want to change the default font for all UITextViews. It seems that the easiest way to do this is via custom category. I found this solution: Change the default systemFont used by controls and tried to implement it.

But my UITextViews are added programmatically so the awakeFromNib function is not called. I tried to move it to initWithFrame like this:

-(id)initWithFrame:(CGRect)frame
{
    id result = [super initWithFrame:frame];
    if (result) {
        float size = [self.font pointSize];
        NSString *stringfontstyle=self.font.fontName;
        if([stringfontstyle rangeOfString:@"Bold"].location != NSNotFound) {
            self.font = [UIFont fontWithName:@"Avenir-Black" size:size];
        }
        else if ([stringfontstyle rangeOfString:@"Italic"].location != NSNotFound) {
            self.font = [UIFont fontWithName:@"Avenir-Oblique" size:size];
        }
        else if ([stringfontstyle rangeOfString:@"Medium"].location != NSNotFound) {
            self.font = [UIFont fontWithName:@"Avenir-Medium" size:size];
        }
        else {
            self.font = [UIFont fontWithName:@"Avenir-Roman" size:size];
        }
    }
    return result;
}

Weird is that if my category contains initWithFrame function, the UITextView disappears. What is it that I'm missing?

Note: I'm using autoLayout so the initWithFrame is called with CGRectZero, but I suppose that isn't the problem.

EDIT:

The problem is that the font is null when the UITextView is initiated. So what method would be appropriate to place the code into?

Community
  • 1
  • 1
adam
  • 807
  • 3
  • 11
  • 17
  • You appear to have subclassing and categories mixed-up. Consider what `super` is in the code you post. I am pretty sure you cannot override methods using a category. – trojanfoe Sep 18 '14 at 14:26
  • So I should make a UITextView subclass and override the setFont function? – adam Sep 18 '14 at 14:28
  • @trojanfoe by the looks of it (http://stackoverflow.com/questions/5272451/overriding-methods-using-categories-in-objective-c) you can override methods using categories but it is discouraged. – Popeye Sep 18 '14 at 14:30

1 Answers1

1

when category contains a method, it overrides the class's method... and thats not good. subclassing would work.. method swizzling might be a way but...

why don't you just subclass UITextView - then you can keep your initWithFrame thingy or maybe override font

- (UIFont*)font {
   if(!myFont) {
      _myFont = xy;
   }

   id superFont = super.font;
   if(![superFont.name isEqualTo:_myFont.name]) {
       super.font = [myFont fontWithSize:superFont.pointSize];
   }
   return _myFont;
}

or setFont:

- (void)setFont:(UIFont*)newFont {
   if(!myFont) {
      _myFont = xy;
   }

   id thisFont = [_myFont fontWithSize:newFont.pointSize];
   super.font = thisFont;
Daij-Djan
  • 49,552
  • 17
  • 113
  • 135