如何在iOS上将UILabels中的文本基线与不同的字体大小对齐? [英] How to align baselines of text in UILabels with different font sizes on iOS?

查看:637
本文介绍了如何在iOS上将UILabels中的文本基线与不同的字体大小对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在UILabels中对齐文本的基线。我目前正在做的是我正在调整包含文本的UILabels的基线,当两个标签中的文本字体大小不同时,这会导致UILabels基线对齐但文本基线未对齐(未对齐不足,但仍然错位)。标签包含在自定义UIView子类中,因此 self 指的是包含UIView。

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 two labels is different, this results in aligned UILabels baseline but misaligned text baseline (misaligned by a small margin, but still misaligned). The labels are included in a custom UIView subclass, therefore self refers to the encompassing UIView.

这里是相关的代码

[self.mySmallLabel sizeToFit];
[self.myBigLabel sizeToFit];

self.mySmallLabel.frame = CGRectMake(0,     
                                     self.bounds.size.height - self.mySmallLabel.bounds.size.height, 
                                     self.mySmallLabel.bounds.size.width, 
                                     self.mySmallLabel.bounds.size.height);

self.myBigLabel.frame = CGRectMake(self.mySmallLabel.frame.origin.x + self.mySmallLabel.bounds.size.width, 
                                   self.bounds.size.height - self.myBigLabel.bounds.size.height, 
                                   self.myBigLabel.bounds.size.width, 
                                   self.myBigLabel.bounds.size.height);
[self.mySmallLabel sizeToFit];
[self.myBigLabel sizeToFit];

此代码会在下面链接的图片中显示对齐。

This code results in the aligment in the image linked below.

当你可以看出,即使UILabel基线对齐,文本的基线也会略微错位。如何动态对齐文本的基线(因为字体大小可能会在运行时更改)?

As you can see, even though the UILabel baselines are aligned, the baselines of the text is misaligned by a small margin. How can I align the baselines of text dynamically (because font sizes might change at runtime)?

推荐答案

我正在使用这个答案在几个不同的地方,但基线有时在Retina显示器上关闭像素。下面的代码段说明了屏幕的比例:

I was using this answer in a couple of different places, but the baselines were sometimes a pixel off on Retina displays. The snippet below accounts for the screen’s scale:

[majorLabel sizeToFit];
[minorLabel sizeToFit];

CGRect changedFrame = minorLabel.frame;
changedFrame.origin.x = CGRectGetWidth(majorLabel.frame);

const CGFloat scale = [UIScreen mainScreen].scale;
const CGFloat majorLabelBaselineInSuperView = CGRectGetMaxY(majorLabel.frame) + majorLabel.font.descender;
const CGFloat minorLabelBaselineInOwnView = CGRectGetHeight(minorLabel.frame) + minorLabel.font.descender;
changedFrame.origin.y = ceil((majorLabelBaselineInSuperView - minorLabelBaselineInOwnView) * scale) / scale;

minorLabel.frame = changedFrame;

这篇关于如何在iOS上将UILabels中的文本基线与不同的字体大小对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆