Skip to content

Commit

Permalink
Fix TextInput vertical alignment issue when using lineHeight prop on …
Browse files Browse the repository at this point in the history
…iOS without changing Text baseline (Fabric - new arch) (#350)
  • Loading branch information
fabOnReact authored May 21, 2024
1 parent edee998 commit b6ba8fe
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions ios/RCTMarkdownUtils.mm
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,8 @@ - (NSAttributedString *)parseMarkdown:(nullable NSAttributedString *)input withA
}
}];

RCTApplyBaselineOffset(attributedString);

[attributedString endEditing];

_prevInputString = inputString;
Expand All @@ -148,4 +150,47 @@ - (NSAttributedString *)parseMarkdown:(nullable NSAttributedString *)input withA
}
}

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

@end

0 comments on commit b6ba8fe

Please sign in to comment.