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.
However, I want a result like this.
How can I achive to this look? Thanks in advance
CodePudding user response:
Add Addditional 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
CodePudding user response:
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).