美文网首页大前端开发
iOS开发中的字体加粗fontWeight

iOS开发中的字体加粗fontWeight

作者: link_hui | 来源:发表于2018-02-22 14:33 被阅读31次

    问题

    设计师同学说有个标题的字体应该加粗,需要修改下。

    解决

    检查后发现代码中忽略了字体的粗细属性。

    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);
    

    相关文章

      网友评论

        本文标题:iOS开发中的字体加粗fontWeight

        本文链接:https://www.haomeiwen.com/subject/ztfztftx.html