如何更改属性字符串中字符的对齐方式

How to change the allignment of a character in Attributed String

这就是我想要实现的。

我使用了一个 attributedString,获取了字符范围 $ 并像下面这样对其应用了属性:

let str = ""
let r1 = str.range(of: "$")!
let n1 = NSRange(r1, in: str)
let atrStr = NSMutableAttributedString(string: str)
atrStr.addAttributes([NSAttributedStringKey.font : UIFont.systemFont(ofSize: 25)], range: n1)
atrStr.addAttributes([NSAttributedStringKey.foregroundColor : UIColor.lightGray], range: n1)
lbl.attributedText = atrStr

但是结果是

如何将该特定字符的对齐方式从下到上更改?

您需要使用 baselineOffsetNSMutableAttributedString

计算两种字体大小的差异

let offset = baseFont.capHeight - smallFont.capHeight

添加名为 baselineOffset 的新属性

atrStr.addAttributes([NSAttributedString.Key.baselineOffset:offset], range: n1)