在iOS中加载xib时会调用API吗?

时间:2016-03-01 02:41:09

标签: ios storyboard xib

当我打开一个xib文件作为源代码时,我发现了一些代码:

<fontDescription key="fontDescription" type="system" pointSize="16"/>

加载此xib文件时,是否会调用UIFont API?

1 个答案:

答案 0 :(得分:1)

是的,它调用UIFont API。我测试了这个:

//
//  UIFont+Swizzled.m
//  Test
//
//  Created by Brandon T on 2016-02-29.
//  Copyright © 2016 Test. All rights reserved.
//

#import "UIFont+Swizzled.h"
#import <objc/runtime.h>

@implementation UIFont (Swizzled)

+ (void)load {
    //Quick and dirty swizzle. Should really only run once and check if method is added.. but w/e..

    Method original, swizzled;

    original = class_getClassMethod(self, @selector(fontWithName:size:));
    swizzled = class_getClassMethod(self, @selector(fontWithNameX:size:));
    method_exchangeImplementations(original, swizzled);

    original = class_getClassMethod(self, @selector(fontWithSize:));
    swizzled = class_getClassMethod(self, @selector(fontWithSizeX:));
    method_exchangeImplementations(original, swizzled);

    original = class_getClassMethod(self, @selector(systemFontOfSize:));
    swizzled = class_getClassMethod(self, @selector(systemFontOfSizeX:));
    method_exchangeImplementations(original, swizzled);

    original = class_getClassMethod(self, @selector(fontWithDescriptor:size:));
    swizzled = class_getClassMethod(self, @selector(fontWithDescriptorX:size:));
    method_exchangeImplementations(original, swizzled);
}

+ (nullable UIFont *)fontWithNameX:(NSString *)fontName size:(CGFloat)fontSize {
    return [self fontWithNameX:fontName size:fontSize];
}

- (UIFont *)fontWithSizeX:(CGFloat)fontSize {
    return [self fontWithSizeX:fontSize];
}

+ (UIFont *)systemFontOfSizeX:(CGFloat)fontSize {
    return [self systemFontOfSizeX:fontSize];
}

+ (UIFont *)fontWithDescriptorX:(UIFontDescriptor *)descriptor size:(CGFloat)pointSize {
    return [self fontWithDescriptorX:descriptor size:pointSize];
}
@end

然后我创建了一个带有单个控制器的空白故事板,为其添加了标签,并将字体更改为大小为17的Helvetica Neue。

接下来,我将上述类别文件包含在与故事板相关联的控制器中。

//
//  ViewController.m
//  Test
//
//  Created by Brandon T on 2016-02-27.
//  Copyright © 2016 Test. All rights reserved.
//

#import "ViewController.h"
#import "UIFont+Swizzled.h"

@interface ViewController ()

@end

@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

结果:

2016-02-29 22:12:19.585 Test[94691:4139779] systemFontOfSize -- Size:17.000000

2016-02-29 22:12:19.586 Test[94691:4139779] fontWithDescriptor  -- Descriptor: UICTFontDescriptor <0x7fe60340e770> = {
    NSFontNameAttribute = HelveticaNeue;
    NSFontSizeAttribute = 17;
}, Size:17.000000

所以它称之为两件事。首先SystemFontOfSize然后调用FontWithDescriptor