在UILabel中对齐不同大小的文本 [英] Top-aligning text of different sizes within a UILabel
问题描述
如何在UILabel中对齐不同大小的文本?一个例子是在价格横幅中将较小尺寸的分金额与较大的美元金额进行顶部对齐。
How to top-align text of different sizes within a UILabel? An example is top-aligning smaller-sized cent amount with larger-sized dollar amount in price banners.
iOS6中的UILabel支持 NSAttributedString
,这使我可以拥有同一UILabel中不同大小的文本。但是它似乎没有顶部对齐文本的属性。有什么选择来实现这个?在我看来,提供一个自定义绘图逻辑来根据自定义属性字符串键进行顶部对齐可能是最好的,但我不知道如何去做。
UILabel in iOS6 supports NSAttributedString
which allows me to have text of different sizes in the same UILabel. However it doesn't seem to have an attribute for top-aligning text. What are the options to implement this? It seems to me that providing a custom drawing logic to do top-alignment based on a custom attributed string key might be best but I have no idea how to go about it.
推荐答案
我能够使用单一标签获得您想要的结果。
I was able to achieve your desired result using a single label.
使用一点数学,您可以抵消基线的较小的文字以达到您想要的效果。
Using a little math you can offset the baseline of the smaller text to achieve your desired result.
Objective-C
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
}
}
这会产生以下:
这篇关于在UILabel中对齐不同大小的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!