NSMutableAttributedString中的NSTextAttachment垂直对齐 [英] Vertically aligning NSTextAttachment in NSMutableAttributedString
问题描述
我正在像这样在NSMutableAttributedString
中使用NSTextAttachment
向UILabel
添加图标:
I'm adding an icon to a UILabel
using NSTextAttachment
inside an NSMutableAttributedString
like this:
//Setting up icon
let moneyIcon = NSTextAttachment()
moneyIcon.image = UIImage(named: "MoneyIcon")
let moneyIconString = NSAttributedString(attachment: moneyIcon)
//Setting up text
let balanceString = NSMutableAttributedString(string: " 1,702,200")
balanceString.insert(moneyIconString, at: 0)
//Adding string to label
self.attributedText = balanceString
self.sizeToFit()
但是由于某种原因,图标未垂直对齐
But for some reason the icon isn't vertically aligned
有人知道我如何对齐它吗?
Does anybody know how can I align it?
谢谢!
推荐答案
此答案,即将两个垂直居中单个NSAttributedString
中大小不同的字体,提到使用基线偏移量来计算字符串的中心.
This answer, which is about vertically centering two differently sized fonts in a single NSAttributedString
, mentions using the baseline offset to calculate the center of the string.
使用图像时可以使用相同的方法:
You can use the same approach when using an image:
-
从图像高度中减去字体大小,然后将其除以2.
Subtract the font size from the image's height and divide it by 2.
从该值中减去字体的降序(因为字体大小与字体的升序不同).您特别使用的字体( Baloo-Regular )的降序值不同于标准字体,应除以2.其他字体(包括San Fransisco)不需要此修复程序或要求使用其他除数.
Subtract the font's descender from the value (since font size isn't the same as the ascent of your font). The font that you are particularly using (Baloo-Regular) has a descender value that differs from the standard and it should be divided by 2. Other fonts (including San Fransisco) don't need that fix or require a different divisor.
This code covers most cases, if your font behaves differently, you should check out the guide for managing texts in Text Kit.
// *Setting up icon*
let moneyIcon = NSTextAttachment()
// If you're sure a value is not and will never be nil, you can use "!".
// Otherwise, avoid it.
let moneyImage = UIImage(named: "MoneyIcon")!
moneyIcon.image = moneyImage
let moneyIconString = NSAttributedString(attachment: moneyIcon)
// *Setting up NSAttributedString attributes*
let balanceFontSize: CGFloat = 16
let balanceFont = UIFont(name: "Baloo", size: balanceFontSize)!
let balanceBaselineOffset: CGFloat = {
let dividend = moneyImage.size.height - balanceFontSize
return dividend / 2 - balanceFont.descender / 2
}()
let balanceAttr: [NSAttributedString.Key: Any] = [
.font: balanceFont,
.baselineOffset: balanceBaselineOffset
]
// *Setting up text*
let balanceString = NSMutableAttributedString(
string: " 1,702,200",
attributes: balanceAttr
)
balanceString.insert(moneyIconString, at: 0)
这篇关于NSMutableAttributedString中的NSTextAttachment垂直对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!