From bb9bf2616956cfc3559642a847b113ea905aa6e6 Mon Sep 17 00:00:00 2001 From: Valentin Shergin Date: Fri, 8 Jun 2018 20:16:15 -0700 Subject: [PATCH] Fabric: Using exact UIFontWeight* constants instead of CGFloat Summary: SUDDENLY, `-[UIFont systemFontOfSize:weight:]` returns incorrect result if `weight` is not exactly equal to any of built-in constants. Reviewed By: fkgozali Differential Revision: D8246712 fbshipit-source-id: 13d59cc8d66a4494437f28d791fd93fa83ebe6fb --- .../fabric/textlayoutmanager/RCTFontUtils.mm | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/ReactCommon/fabric/textlayoutmanager/RCTFontUtils.mm b/ReactCommon/fabric/textlayoutmanager/RCTFontUtils.mm index 38a3d80f5..954051f86 100644 --- a/ReactCommon/fabric/textlayoutmanager/RCTFontUtils.mm +++ b/ReactCommon/fabric/textlayoutmanager/RCTFontUtils.mm @@ -7,6 +7,7 @@ #import "RCTFontUtils.h" +#import #import static RCTFontProperties RCTDefaultFontProperties() { @@ -55,6 +56,25 @@ static NSArray *RCTFontFeatures(RCTFontVariant fontVariant) { return @[]; } +static UIFontWeight RCTUIFontWeightFromFloat(CGFloat fontWeight) { + // Note: Even if the underlying type of `UIFontWeight` is `CGFloat` + // and UIKit uses the same numerical notation, we have to use exact + // `UIFontWeight*` constants to make it work properly (because + // float values comparison is tricky). + static UIFontWeight weights[] = { + /* ~100 */ UIFontWeightUltraLight, + /* ~200 */ UIFontWeightThin, + /* ~300 */ UIFontWeightLight, + /* ~400 */ UIFontWeightRegular, + /* ~500 */ UIFontWeightMedium, + /* ~600 */ UIFontWeightSemibold, + /* ~700 */ UIFontWeightBold, + /* ~800 */ UIFontWeightHeavy, + /* ~900 */ UIFontWeightBlack + }; + return weights[std::llround((fontWeight / 100) - 1)]; +} + static UIFont *RCTDefaultFontWithFontProperties(RCTFontProperties fontProperties) { static NSCache *fontCache; static std::mutex fontCacheMutex; @@ -72,7 +92,7 @@ static UIFont *RCTDefaultFontWithFontProperties(RCTFontProperties fontProperties if (!font) { font = [UIFont systemFontOfSize:fontProperties.size - weight:fontProperties.weight]; + weight:RCTUIFontWeightFromFloat(fontProperties.weight)]; if (fontProperties.variant == RCTFontStyleItalic) { UIFontDescriptor *fontDescriptor = [font fontDescriptor]; @@ -114,7 +134,7 @@ UIFont *RCTFontWithFontProperties(RCTFontProperties fontProperties) { if (!font) { // Failback to system font. - font = [UIFont systemFontOfSize:effectiveFontSize weight:fontProperties.weight]; + font = [UIFont systemFontOfSize:effectiveFontSize weight:RCTUIFontWeightFromFloat(fontProperties.weight)]; } } else { // Get the closest font that matches the given weight for the fontFamily