ios - UILabel 中不同大小的顶部对齐文本

标签 ios ios6 uilabel nsattributedstring

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

Sample Image

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

最佳答案

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

使用一些数学知识,您可以偏移较小文本的基线以获得您想要的结果。

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

swift

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
    }
}

这会产生以下结果:

关于ios - UILabel 中不同大小的顶部对齐文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15537033/

相关文章:

ios - 为 View 中的所有标签设置自定义字体

ios - UILabel 截断

ios - 如何使用一个tableview的按钮自动选择另一个tableview的按钮全部

ios - onTapGesture禁用我的“选择器”和“分割”点击

ios - Swift:与点 (".") 文字相关的自定义运算符的优先级

ios - 快速从字符串中提取值

objective-c - 每个分段的UISegmentedControl自定义图像

ios - 何时以及如何关闭 UIActivityViewController

ios - 从 CLGeocoder 获取当前城市和国家?

cocoa - 更改 NSTextField 字体大小以适应