iphone - 如何在 iOS 上使用不同字体大小对齐 UILabels 中的文本基线?

标签 iphone ios ios4

我需要对齐 UILabel 中文本的基线。我目前正在做的是对齐包含文本的 UILabels 的基线,当两个标签中的文本字体大小不同时,这会导致 UILabels 基线对齐但文本基线未对齐(略微未对齐,但仍然错位)。标签包含在自定义 UIView 子类中,因此 self 指的是包含的 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];

此代码导致下面链接的图像中的对齐。

Misalignemnt

如您所见,即使 UILabel 基线对齐,文本的基线也有一点点错位。如何动态对齐文本的基线(因为字体大小可能会在运行时发生变化)?

最佳答案

我正在使用 this answer在几个不同的地方,但基线有时在 Retina 显示器上有一个像素的偏差。下面的代码片段说明了屏幕的比例:

[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;

关于iphone - 如何在 iOS 上使用不同字体大小对齐 UILabels 中的文本基线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9910766/

相关文章:

iPhone UITableView 单元格的奇怪行为

iphone - MKMapView 和 dequeueReusableAnnotationViewWithIdentifier :

iOS - 点击后弹出自定义 subview

iphone - UIButton图像和背景图像,使用哪一个作为自定义图像?

ios - 查看 iPad/iPhone 的文件系统以验证保存的文件

ios - SpriteKit 中的动画路径绘制

objective-c - 如何在 GCD block 中指定返回类型

ios - CollectionView 单元出现在 collectionView 之外。

iPhone应用程序使用150 MB内存,仍然没有内存不足警告!

objective-c - 在 iPad 模拟器上运行但在 iPad 上崩溃