Skip to content

Commit 70cc27c

Browse files
sammy-SCfacebook-github-bot
authored andcommitted
Center text if line height isn't 0
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
1 parent 712fcde commit 70cc27c

File tree

1 file changed

+45
-1
lines changed

1 file changed

+45
-1
lines changed

ReactCommon/react/renderer/textlayoutmanager/platform/ios/RCTAttributedTextUtils.mm

+45-1
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,50 @@ inline static CGFloat RCTEffectiveFontSizeMultiplierFromTextAttributes(const Tex
305305
return [attributes copy];
306306
}
307307

308+
static void RCTApplyBaselineOffset(NSMutableAttributedString *attributedText)
309+
{
310+
__block CGFloat maximumLineHeight = 0;
311+
312+
[attributedText enumerateAttribute:NSParagraphStyleAttributeName
313+
inRange:NSMakeRange(0, attributedText.length)
314+
options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired
315+
usingBlock:^(NSParagraphStyle *paragraphStyle, __unused NSRange range, __unused BOOL *stop) {
316+
if (!paragraphStyle) {
317+
return;
318+
}
319+
320+
maximumLineHeight = MAX(paragraphStyle.maximumLineHeight, maximumLineHeight);
321+
}];
322+
323+
if (maximumLineHeight == 0) {
324+
// `lineHeight` was not specified, nothing to do.
325+
return;
326+
}
327+
328+
__block CGFloat maximumFontLineHeight = 0;
329+
330+
[attributedText enumerateAttribute:NSFontAttributeName
331+
inRange:NSMakeRange(0, attributedText.length)
332+
options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired
333+
usingBlock:^(UIFont *font, NSRange range, __unused BOOL *stop) {
334+
if (!font) {
335+
return;
336+
}
337+
338+
maximumFontLineHeight = MAX(font.lineHeight, maximumFontLineHeight);
339+
}];
340+
341+
if (maximumLineHeight < maximumFontLineHeight) {
342+
return;
343+
}
344+
345+
CGFloat baseLineOffset = (maximumLineHeight - maximumFontLineHeight) / 2.0;
346+
347+
[attributedText addAttribute:NSBaselineOffsetAttributeName
348+
value:@(baseLineOffset)
349+
range:NSMakeRange(0, attributedText.length)];
350+
}
351+
308352
NSAttributedString *RCTNSAttributedStringFromAttributedString(const AttributedString &attributedString)
309353
{
310354
static UIImage *placeholderImage;
@@ -357,7 +401,7 @@ inline static CGFloat RCTEffectiveFontSizeMultiplierFromTextAttributes(const Tex
357401

358402
[nsAttributedString appendAttributedString:nsAttributedStringFragment];
359403
}
360-
404+
RCTApplyBaselineOffset(nsAttributedString);
361405
[nsAttributedString endEditing];
362406

363407
return nsAttributedString;

0 commit comments

Comments
 (0)