iOS开发中的字体加粗fontWeight
2018-02-22 本文已影响31人
link_hui
问题
设计师同学说有个标题的字体应该加粗,需要修改下。
解决
检查后发现代码中忽略了字体的粗细属性。
UIFont *font = [UIFont systemFontOfSize:fontSize];
这个方法是不支持设置字体粗细的。实际上系统提供了设置字体的粗细的方法。
+ (UIFont *)boldSystemFontOfSize:(CGFloat)fontSize;
+ (UIFont *)systemFontOfSize:(CGFloat)fontSize weight:(UIFontWeight)weight NS_AVAILABLE_IOS(8_2);
需要注意的是下面这个weight设置的方法只是在iOS8.2开始的版本生效。修改后设置字体的方法如下:
if(([[[UIDevice currentDevice] systemVersion] compare:@"8.2" options:NSNumericSearch] == NSOrderedAscending)) {
font = [UIFont systemFontOfSize:fontSize];
} else {
font = [UIFont systemFontOfSize:fontSize weight:textWeight];
}
扩展
- fontWeight是描述字体粗细程度的属性,我们平时比较少注意到。另外iOS中定义了UIFontWeight的一些常量
UIKIT_EXTERN const UIFontWeight UIFontWeightUltraLight NS_AVAILABLE_IOS(8_2);
UIKIT_EXTERN const UIFontWeight UIFontWeightThin NS_AVAILABLE_IOS(8_2);
UIKIT_EXTERN const UIFontWeight UIFontWeightLight NS_AVAILABLE_IOS(8_2);
UIKIT_EXTERN const UIFontWeight UIFontWeightRegular NS_AVAILABLE_IOS(8_2);
UIKIT_EXTERN const UIFontWeight UIFontWeightMedium NS_AVAILABLE_IOS(8_2);
UIKIT_EXTERN const UIFontWeight UIFontWeightSemibold NS_AVAILABLE_IOS(8_2);
UIKIT_EXTERN const UIFontWeight UIFontWeightBold NS_AVAILABLE_IOS(8_2);
UIKIT_EXTERN const UIFontWeight UIFontWeightHeavy NS_AVAILABLE_IOS(8_2);
UIKIT_EXTERN const UIFontWeight UIFontWeightBlack NS_AVAILABLE_IOS(8_2);
- 另外在CSS中关于font-weight的描述是比较详细的,可以参考CSS font-weight 属性和font-weight里面的说明。