0%

UIFontWeightTrait 的一些坑

IOS客户端中使用font-weight属性来设置字体

1、配置font-weight (-1.0~1.0)

1
2
3
4
5
static std::vector<CGFloat> fontWeightConfig = {
-1.00, UIFontWeightThin, UIFontWeightUltraLight, UIFontWeightLight,
UIFontWeightRegular, UIFontWeightMedium, UIFontWeightSemibold,
UIFontWeightBold, UIFontWeightHeavy, UIFontWeightBlack, 1.00
};

2、通过 systemFontOfSize 和 fontWithDescriptor 创建字体

systemFontOfSize

1
2
3
4
5
6
7
8
9
10
11
12
13
- (IBAction)onClickSysFont:(id)sender {
int size = 20;
for (int i = 0; i < (int)fontWeightConfig.size(); ++ i) {
CGFloat fontWeigth = fontWeightConfig[i];
UIFont* font = [UIFont systemFontOfSize:size weight:fontWeigth];
UILabel* lb = (UILabel*)[self.view viewWithTag:(100 + i)];
if (!font || !lb) {
continue;
}

lb.font = font;
}
}

fontWithDescriptor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
- (IBAction)onClickCusFont:(id)sender {
int size = 20;
for (int i = 0; i < (int)fontWeightConfig.size(); ++ i) {
CGFloat fontWeigth = fontWeightConfig[i];

UIFontDescriptorSymbolicTraits symbolic = 0;

symbolic |= UIFontDescriptorTraitBold;
symbolic |= UIFontDescriptorTraitItalic;

UIFontDescriptor* fontDescriptor = [UIFontDescriptor fontDescriptorWithFontAttributes:@{
UIFontDescriptorSizeAttribute:@(size),
UIFontDescriptorFamilyAttribute: @"Helvetica Neue",
UIFontDescriptorTraitsAttribute: @{
UIFontWeightTrait: @(fontWeigth),
},
}];

UIFont* font = [UIFont fontWithDescriptor:fontDescriptor size:size];

UILabel* lb = (UILabel*)[self.view viewWithTag:(100 + i)];
if (!font || !lb) {
continue;
}

lb.font = font;
}
}

3、效果

4、注意事项

部分字体不支持更多的font-weight设置,比如Arial字体,只支持normal和bold属性;

部分字体不支持自定义的font-weight值,需要使用系统定义的值;

5、demo路径

https://github.com/hilive/samples/tree/master/ios/font-test

用户的需求就是我的追求!