我在UILabel
中使用NSTextAttachment
在NSMutableAttributedString
中添加了一个图标,如下所示:
//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()
但由于某种原因,图标不是垂直对齐的
有谁知道如何对齐它?
谢谢!
This answer,在一个NSAttributedString
中垂直居中两个不同大小的字体,提到使用基线偏移量来计算字符串的中心。
使用图像时可以使用相同的方法:
此代码涵盖大多数情况,如果您的字体行为不同,您应该查看the guide for managing texts in Text Kit。
let moneyImage = UIImage(named: "MoneyIcon")!
//Setting up icon
let moneyIcon = NSTextAttachment()
moneyIcon.image = moneyImage
let moneyIconString = NSAttributedString(attachment: moneyIcon)
let balanceFontSize: CGFloat = 16
let balanceFont = UIFont(name: "Baloo", size: balanceFontSize)
//Setting up font and the baseline offset of the string, so that it will be centered
let balanceAttr: [NSAttributedStringKey: Any] = [.font: balanceFont,
.baselineOffset: (moneyImage.size.height - balanceFontSize) / 2 - balanceFont.descender / 2]
//Setting up text
let balanceString = NSMutableAttributedString(string: " 1,702,200", attributes: balanceAttr)
balanceString.insert(moneyIconString, at: 0)
使用bounds
的NSTextAttachment
属性。
//Setting up icon
let moneyIcon = NSTextAttachment()
moneyIcon.image = UIImage(named: "MoneyIcon")
let imageSize = moneyIcon.image!.size
moneyIcon.bounds = CGRect(x: CGFloat(0), y: (font.capHeight - imageSize.height) / 2, width: imageSize.width, height: imageSize.height)
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()