Add degree sign to a label with different font sizes - Swift

203 Views Asked by At

I am building a weather app. In this app, I am showing the temperature value to the user. In this value, I want to make the temperature value and degree sign different sizes. Because when the degree sign is the same size as the temperature value it alters the center of the view.

I try the NSAttributedText way like this.

   let attrString = NSMutableAttributedString(string: temperature.value,
                                                 attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 36)])

      attrString.append(NSMutableAttributedString(string:"°",
                                                  attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18)]))
      temperature = attrString

I try the Unicode version "\u{00B0}" of the degree sign too. It doesn't matter by the way.

The result was like this. enter image description here

However, I want a result like this. enter image description here

How can I achive to this look? Thanks in advance

2

There are 2 best solutions below

0
Noman Umar On BEST ANSWER

Add additional attributes .baselineOffset: NSNumber(value: 18) where you add "°" in temperature.value:

let attrString = NSMutableAttributedString(string: temperature.value,
                                                         attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 36)])

attrString.append(NSMutableAttributedString(string:"°",
                                                    attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18),.baselineOffset: NSNumber(value: 18)]))
temperature = attrString
    
0
HangarRash On

One solution would be to make use of the .baselineOffset key. Add this to the attributes dictionary for the degree symbol:

.baselineOffset: 16

Adjust the number to get the exact position you want. The bigger the number the higher up the degree symbol will appear.

You might also want to try playing around with the .kern attribute key as well if you want the characters to appear closer together (use a negative value).