Skip to content

Commit

Permalink
Center text if line height isn't 0
Browse files Browse the repository at this point in the history
Summary: changelog: Fix vertical text alignment in new architecture when line height is not 0.

Reviewed By: javache

Differential Revision: D40346225

fbshipit-source-id: f6282cb8df80e9a543e5602fddcca1a1a82377e3
  • Loading branch information
sammy-SC authored and facebook-github-bot committed Oct 14, 2022
1 parent 712fcde commit 70cc27c
Showing 1 changed file with 45 additions and 1 deletion.
Expand Up @@ -305,6 +305,50 @@ inline static CGFloat RCTEffectiveFontSizeMultiplierFromTextAttributes(const Tex
return [attributes copy];
}

static void RCTApplyBaselineOffset(NSMutableAttributedString *attributedText)
{
__block CGFloat maximumLineHeight = 0;

[attributedText enumerateAttribute:NSParagraphStyleAttributeName
inRange:NSMakeRange(0, attributedText.length)
options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired
usingBlock:^(NSParagraphStyle *paragraphStyle, __unused NSRange range, __unused BOOL *stop) {
if (!paragraphStyle) {
return;
}

maximumLineHeight = MAX(paragraphStyle.maximumLineHeight, maximumLineHeight);
}];

if (maximumLineHeight == 0) {
// `lineHeight` was not specified, nothing to do.
return;
}

__block CGFloat maximumFontLineHeight = 0;

[attributedText enumerateAttribute:NSFontAttributeName
inRange:NSMakeRange(0, attributedText.length)
options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired
usingBlock:^(UIFont *font, NSRange range, __unused BOOL *stop) {
if (!font) {
return;
}

maximumFontLineHeight = MAX(font.lineHeight, maximumFontLineHeight);
}];

if (maximumLineHeight < maximumFontLineHeight) {
return;
}

CGFloat baseLineOffset = (maximumLineHeight - maximumFontLineHeight) / 2.0;

[attributedText addAttribute:NSBaselineOffsetAttributeName
value:@(baseLineOffset)
range:NSMakeRange(0, attributedText.length)];
}

NSAttributedString *RCTNSAttributedStringFromAttributedString(const AttributedString &attributedString)
{
static UIImage *placeholderImage;
Expand Down Expand Up @@ -357,7 +401,7 @@ inline static CGFloat RCTEffectiveFontSizeMultiplierFromTextAttributes(const Tex

[nsAttributedString appendAttributedString:nsAttributedStringFragment];
}

RCTApplyBaselineOffset(nsAttributedString);
[nsAttributedString endEditing];

return nsAttributedString;
Expand Down

0 comments on commit 70cc27c

Please sign in to comment.