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