在NSMutableAttributedString中垂直对齐NSTextAttachment

问题描述 投票:1回答:2

我在UILabel中使用NSTextAttachmentNSMutableAttributedString中添加了一个图标,如下所示:

//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()

但由于某种原因,图标不是垂直对齐的

有谁知道如何对齐它?

谢谢!

ios swift uilabel nsattributedstring
2个回答
3
投票

This answer,在一个NSAttributedString中垂直居中两个不同大小的字体,提到使用基线偏移量来计算字符串的中心。

使用图像时可以使用相同的方法:

  1. 从图像的高度减去字体大小并将其除以2。
  2. 从值中减去字体的下划线(因为字体大小与字体的上升不同)。您特别使用的字体(Baloo-Regular)具有与标准不同的下行值,它应除以2.其他字体(包括San Fransisco)不需要该修复或需要不同的除数。

此代码涵盖大多数情况,如果您的字体行为不同,您应该查看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)

Here is a GitHub project where you can try out this code.


0
投票

使用boundsNSTextAttachment属性。

//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()
© www.soinside.com 2019 - 2024. All rights reserved.