在UILabel中对齐不同大小的文本

eje*_*jel 22 nsattributedstring uilabel ios ios6

如何在UILabel中顶部对齐不同大小的文本?一个例子是在价格横幅中将较小尺寸的分金额与较大尺寸的金额进行顶部对齐.

示例图像

iOS6中的UILabel支持NSAttributedString允许我在同一个UILabel中使用不同大小的文本.但是它似乎没有顶部对齐文本的属性.有什么选择来实现这个?在我看来,提供自定义绘图逻辑来基于自定义属性字符串键进行顶部对齐可能是最好的,但我不知道如何去做.

Eri*_*hey 47

我能够使用单个标签实现您想要的结果.

使用一点数学,您可以偏移较小文本的基线,以达到您想要的结果.

Objective-C的

- (NSMutableAttributedString *)styleSalePriceLabel:(NSString *)salePrice withFont:(UIFont *)font
{
    if ([salePrice rangeOfString:@"."].location == NSNotFound) {
        return [[NSMutableAttributedString alloc] initWithString:salePrice];
    } else {
        NSRange range = [salePrice rangeOfString:@"."];
        range.length = (salePrice.length - range.location);
        NSMutableAttributedString *stylizedPriceLabel = [[NSMutableAttributedString alloc] initWithString:salePrice];
        UIFont *smallFont = [UIFont fontWithName:font.fontName size:(font.pointSize / 2)];
        NSNumber *offsetAmount = @(font.capHeight - smallFont.capHeight);
        [stylizedPriceLabel addAttribute:NSFontAttributeName value:smallFont range:range];
        [stylizedPriceLabel addAttribute:NSBaselineOffsetAttributeName value:offsetAmount range:range];
        return stylizedPriceLabel;
    }
}
Run Code Online (Sandbox Code Playgroud)

迅速

extension Range where Bound == String.Index {
    func asNSRange() -> NSRange {
        let location = self.lowerBound.encodedOffset
        let length = self.lowerBound.encodedOffset - self.upperBound.encodedOffset
        return NSRange(location: location, length: length)
    }
}

extension String {
    func asStylizedPrice(using font: UIFont) -> NSMutableAttributedString {
        let stylizedPrice = NSMutableAttributedString(string: self, attributes: [.font: font])

        guard var changeRange = self.range(of: ".")?.asNSRange() else {
            return stylizedPrice
        }

        changeRange.length = self.count - changeRange.location
        // forgive the force unwrapping
        let changeFont = UIFont(name: font.fontName, size: (font.pointSize / 2))!
        let offset = font.capHeight - changeFont.capHeight
        stylizedPrice.addAttribute(.font, value: changeFont, range: changeRange)
        stylizedPrice.addAttribute(.baselineOffset, value: offset, range: changeRange)
        return stylizedPrice
    }
}
Run Code Online (Sandbox Code Playgroud)

这产生以下结果:


小智 10

简单地通过对齐框架的起源来尝试这样做的问题在于,"普通"字符通常最终会在它们周围添加一些额外的填充,因为标签必须容纳所有字体的字符,包括高的上升和长下降.您会注意到,在您发布的图片中,如果较小的"99"是与较大文本设置为相同原点的单独标签,则由于美元符号的最高点而过高.

幸运的是,UIFont为我们提供了正确执行此操作所需的所有信息.我们需要测量标签使用的空的上升空间并调整相对位置来解释它,如下所示:

//Make sure the labels hug their contents
[self.bigTextLabel sizeToFit];
[self.smallTextLabel sizeToFit];

//Figure out the "blank" space above normal character height for the big text
UIFont *bigFont = self.bigTextLabel.font;
CGFloat bigAscenderSpace = (bigFont.ascender - bigFont.capHeight);

//Move the small text down by that ammount
CGFloat smallTextOrigin = CGRectGetMinY(self.bigTextLabel.frame) + bigAscenderSpace;

//Figure out the "blank" space above normal character height for the little text
UIFont *smallFont = self.smallTextLabel.font;
CGFloat smallAscenderSpace = smallFont.ascender - smallFont.capHeight;

//Move the small text back up by that ammount
smallTextOrigin -= smallAscenderSpace;

//Actually assign the frames
CGRect smallTextFrame = self.smallTextLabel.frame;
smallTextFrame.origin.y = smallTextOrigin;
self.smallTextLabel.frame = smallTextFrame;
Run Code Online (Sandbox Code Playgroud)

(此代码假定您有两个标签的属性命名bigTextLabelsmallTextLabel,分别)


编辑:

没有两个标签这样做是非常相似的.您可以创建一个自定义的UIView子类,并NSAttributedStrings使用该-drawInRect:options:context:方法绘制它(确保NSStringDrawingUsesLineFragmentOrigin在您的选项中使用).计算顶部对齐的数学运算应该是相同的,唯一的区别是您通过NSFontAttributeName属性从属性字符串中获取字体,而不是标签.关于归因字符串绘制的2012 WWDC视频是一个很好的参考.