Search code examples
iosswiftnsmutableattributedstring

How to change the allignment of a character in Attributed String


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?


Solution

  • 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)