開發中我們常常遇到需要自定義字體的情況,蘋果為我們提供了豐富的字體庫,可在mac系統的字體冊中查看,或者直接到系統資源庫~/Font下查看,然而項目中如何高效利用呢。
我們可以通過以下代碼查看系統字體庫的樣式:
//? ? 遍歷字體族
for (NSString * familyName in [UIFont familyNames]) {
//? ? ? ? 字體族科
NSLog(@"familyName = %@",familyName);
for (NSString * fontName in [UIFont fontNamesForFamilyName:familyName])
{
// ? ? ?族科下字體的樣式
NSLog(@"%@",fontName);
}
}
我們經常看到一些有特色的項目可以一鍵切換系統字體,這是怎么做到的呢,如果一個個設置字體樣式顯然是不現實的,而且你如果這么寫:
label3.font = [UIFont fontWithName:@"Americana Dreams Upright" size:30.0f];
你會發現并沒有效果。
那么我們就可以用以下方式:
首先將你需要的字體類型引入工程。添加label的類擴展,然后添加以下兩個方法
+ (void)load {
//方法交換應該被保證,在程序中只會執行一次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//獲得viewController的生命周期方法的selector
SEL systemSel = @selector(willMoveToSuperview:);
//自己實現的將要被交換的方法的selector
SEL swizzSel = @selector(myWillMoveToSuperview:);
//兩個方法的Method
Method systemMethod = class_getInstanceMethod([self class], systemSel);
Method swizzMethod = class_getInstanceMethod([self class], swizzSel);
//首先動態添加方法,實現是被交換的方法,返回值表示添加成功還是失敗
BOOL isAdd = class_addMethod(self, systemSel, method_getImplementation(swizzMethod), method_getTypeEncoding(swizzMethod));
if (isAdd) {
//如果成功,說明類中不存在這個方法的實現
//將被交換方法的實現替換到這個并不存在的實現
class_replaceMethod(self, swizzSel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
} else {
//否則,交換兩個方法的實現
method_exchangeImplementations(systemMethod, swizzMethod);
}
});
}
- (void)myWillMoveToSuperview:(UIView *)newSuperview {
[self myWillMoveToSuperview:newSuperview];
if (self) {
if (self.tag == 10000) {
self.font = [UIFont systemFontOfSize:self.font.pointSize];
} else {
if ([UIFont fontNamesForFamilyName:CustomFontName])
self.font? = [UIFont fontWithName:CustomFontName size:self.font.pointSize];
}
}
}
引入.h文件之后,你可以發現所有label包括button的字體樣式已經是你想設置的。
然而問題又出來了,這時候如果我們需要部分字體格式不變呢?
這時候我們可以定義一個label的子類,實現下邊的兩個方法就可以了。
+ (void)load {
//方法交換應該被保證,在程序中只會執行一次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//獲得viewController的生命周期方法的selector
SEL systemSel = @selector(willMoveToSuperview:);
//自己實現的將要被交換的方法的selector
SEL swizzSel = @selector(myWillMoveToSuperview:);
//兩個方法的Method
Method systemMethod = class_getInstanceMethod([self class], systemSel);
Method swizzMethod = class_getInstanceMethod([self class], swizzSel);
//首先動態添加方法,實現是被交換的方法,返回值表示添加成功還是失敗
BOOL isAdd = class_addMethod(self, systemSel, method_getImplementation(swizzMethod), method_getTypeEncoding(swizzMethod));
if (isAdd) {
//如果成功,說明類中不存在這個方法的實現
//將被交換方法的實現替換到這個并不存在的實現
class_replaceMethod(self, swizzSel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
} else {
//否則,交換兩個方法的實現
method_exchangeImplementations(systemMethod, swizzMethod);
}
});
}
- (void)myWillMoveToSuperview:(UIView *)newSuperview {
[self myWillMoveToSuperview:newSuperview];
if ([UIFont fontNamesForFamilyName:CustomFontName])
self.font? = [UIFont fontWithName:CustomFontName size:self.font.pointSize];
}
相關代碼可到github下載:下載鏈接