如何在 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
}
}
这会产生以下结果:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)