我需要对齐 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];
此代码导致下面链接的图像中的对齐。
如您所见,即使 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/