Ken
Ken

Reputation: 1471

How to add superscript when a button is pressed?

I am trying to make a calculator app and currently all numbers entered are displayed on a UILabel. When the "Power (^)" button is pressed, I want it to make the following text a superscript to what was previously entered (so I want it to be smaller and by the top right corner). So if I enter "2" then "^" then "0", I want it to show 2° (2 to the power 0).

I haven't tried much since I am not even sure where to start, but I was thinking maybe I could create a new UILabel which is smaller and in the top right corner of the last piece of text entered, but I don't know how to know where to place the little UILabel (I don't know how to get the position of the last letter/number).

I have the same problem with the divide, when divide is pressed I want it to be in the form of a fraction with text in the numerator, a horizontal line, and then text under for the denominator. But I have a feeling I will be able to solve both of these if I can figure out how to just solve one.

This is what my app currently looks like >> enter image description here

Upvotes: 0

Views: 224

Answers (2)

SM Abu Taher Asif
SM Abu Taher Asif

Reputation: 2331

I think you don't need another UILabel. There's a answer regarding this in the below link : How to use subscript and superscript in Swift

Upvotes: 0

Nur Choirudin
Nur Choirudin

Reputation: 26

   let font:UIFont? = UIFont.systemFont(ofSize: 20.0)
   let fontSuper:UIFont? = UIFont.systemFont(ofSize: 10.0)
   let attString:NSMutableAttributedString = NSMutableAttributedString(string: "YourLabel", attributes: [.font:font!])
   attString.setAttributes([.font:fontSuper!,.baselineOffset:10], range: NSRange(location:4,length:5))
   yourLabel.attributedText = attString

Upvotes: 1

Related Questions