Ad

How To Change The Allignment Of A Character In Attributed String

- 1 answer

This is what I want to achieve.

enter image description here

I used an attributedString, took the range of character $ and applied attributes to it like below way:

let str = "$4"
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

But the result is

enter image description here

How do I change the allignment of that specific character from bottom to top?

Ad

Answer

You need to use baselineOffset of NSMutableAttributedString

calculate the diference between your two fonts sizes

let offset = baseFont.capHeight - smallFont.capHeight

Add the new attribute called baselineOffset

atrStr.addAttributes([NSAttributedString.Key.baselineOffset:offset], range: n1)
Ad
source: stackoverflow.com
Ad