How to align baselines of text in UILabels with different font sizes on iOS?

前端 未结 5 1848
野性不改
野性不改 2021-01-04 01:13

I need to align the baselines of text in UILabels. What I\'m currently doing is I\'m aligning the baselines of UILabels containing the text, and when the text font size in t

5条回答
  •  攒了一身酷
    2021-01-04 01:34

    You can get pixel-perfect baseline alignment for any pair of UILabels by using the UIFont ascender value in a simple calculation. Here's how:

    [majorLabel sizeToFit];
    [minorLabel sizeToFit];
    
    CGRect changedFrame = minorLabel.frame;
    changedFrame.origin.y = ceilf(majorLabel.frame.origin.y + (majorLabel.font.ascender - minorLabel.font.ascender));
    minorLabel.frame = changedFrame;
    

    ceilf() is used because the font.ascender values may be fractional.

    I've tested this on both retina and non-retina devices, with excellent results. Positioning the two labels relative to each other on the x-axis has been omitted, as your needs may vary. If you need a quick explanation of what the UIFont ascender is (plus other UIFont info) check out this clear, concise article.

提交回复
热议问题