SwiftUI Text - How to convert 10^12 to 10 the correct format
This kind of things are much easier in SwiftUI, there is lots of ways for this job in SwiftUI one of them could be this down code:
struct ContentView: View {
@State var yourFirstText: String = "The universe has "
@State var yourLastText: String = " bla bla bla"
var body: some View {
Text(yourFirstText) + Text("10") + Text("12").font(Font.footnote).baselineOffset(6.0) + Text(yourLastText)
}
}
Is there a SwiftUI way of making text superscript or subscript?
Here's a generic way using .baselineOffset
:
Text("Company")
.font(.callout)
+ Text("TM")
.font(.system(size: 8.0))
.baselineOffset(6.0)
I'm sure there's a way to get the correct offset dynamically using CTFont
, but I think it may be a pain. A sloppy way would be to wrap the Text View(s)? in a GeometryReader, and use the height to try and position it so it looks good.
You can also use Unicode for some symbols (like ™):
Text("Company\u{2122}")
Exponentiation operator in Swift
There isn't an operator but you can use the pow function like this:
return pow(num, power)
If you want to, you could also make an operator call the pow function like this:
infix operator ** { associativity left precedence 170 }
func ** (num: Double, power: Double) -> Double{
return pow(num, power)
}
2.0**2.0 //4.0
How do I use subscript and superscript in Swift?
Most of the answers+examples are in ObjC, but this is how to do it in Swift.
let font:UIFont? = UIFont(name: "Helvetica", size:20)
let fontSuper:UIFont? = UIFont(name: "Helvetica", size:10)
let attString:NSMutableAttributedString = NSMutableAttributedString(string: "6.022*1023", attributes: [.font:font!])
attString.setAttributes([.font:fontSuper!,.baselineOffset:10], range: NSRange(location:8,length:2))
labelVarName.attributedText = attString
This gives me:
In a more detailed explanation:
- Get
UIFont
you want for both the default and superscript style, superscript must be smaller. - Create a
NSMutableAttributedString
with the full string and default font. - Add an attribute to the characters you want to change (
NSRange
), with the smaller/subscriptUIFont
, and theNSBaselineOffsetAttributeName
value is the amount you want to offset it vertically. - Assign it to your
UILabel
Hopefully this helps other Swift devs as I needed this as well.
How to get the Power of some Integer in Swift language?
If you like, you could declare an infix
operator
to do it.
// Put this at file level anywhere in your project
infix operator ^^ { associativity left precedence 160 }
func ^^ (radix: Int, power: Int) -> Int {
return Int(pow(Double(radix), Double(power)))
}
// ...
// Then you can do this...
let i = 2 ^^ 3
// ... or
println("2³ = \(2 ^^ 3)") // Prints 2³ = 8
I used two carets so you can still use the XOR operator.
Update for Swift 3
In Swift 3 the "magic number" precedence
is replaced by precedencegroups
:
precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ^^ : PowerPrecedence
func ^^ (radix: Int, power: Int) -> Int {
return Int(pow(Double(radix), Double(power)))
}
// ...
// Then you can do this...
let i2 = 2 ^^ 3
// ... or
print("2³ = \(2 ^^ 3)") // Prints 2³ = 8
Aligning SwiftUI text to the baseline and top of another text
You can use Stacks to stack font. There is no issue for the bottom line, but You can get help from the UIFont that gives you the information you need like:
struct ContentView: View {
let bigFont = UIFont.systemFont(ofSize: 70)
let smallFont = UIFont.systemFont(ofSize: 24)
var body: some View {
ZStack(alignment: Alignment(horizontal: .leading, vertical: .center)) {
HStack(alignment: .firstTextBaseline, spacing: 0) {
Text("7").font(Font(bigFont))
Text("kts").font(Font(smallFont))
}
HStack(alignment: .firstTextBaseline, spacing: 0) {
Text("7")
.font(Font(bigFont))
.opacity(0)
Text(".0")
.font(Font(smallFont))
.baselineOffset((bigFont.capHeight - smallFont.capHeight))
}
}
}
}
More information:
Here is an image about the description of the Font
for more information:
how to prevent scientific notation with Float in swift
Format your number style :
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.decimal
let finalNumber = numberFormatter.number(from: "\(rangeSlider.lowerValue)")
print(finalNumber!)
With the conversion of simple 1e+07
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.decimal
let finalNumber = numberFormatter.number(from: "\(1e+07)")
print(finalNumber!)
Output :
10000000
Hope this helps.
Convert Double to Scientific Notation in swift
You can set NumberFormatter properties positiveFormat and exponent Symbol to format your string as you want as follow:
let val = 500
let formatter = NumberFormatter()
formatter.numberStyle = .scientific
formatter.positiveFormat = "0.###E+0"
formatter.exponentSymbol = "e"
if let scientificFormatted = formatter.string(for: val) {
print(scientificFormatted) // "5e+2"
}
update: Xcode 9 • Swift 4
You can also create an extension to get a scientific formatted description from Numeric types as follow:
extension Formatter {
static let scientific: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .scientific
formatter.positiveFormat = "0.###E+0"
formatter.exponentSymbol = "e"
return formatter
}()
}
extension Numeric {
var scientificFormatted: String {
return Formatter.scientific.string(for: self) ?? ""
}
}
print(500.scientificFormatted) // "5e+2"
Related Topics
What Does the Underscore in a Function Declaration Do
Don't Delete Some Rows from Uitableview
Xcode Gm: No Swift Language for Os X Command Line Tool Project
Example for Drag and Drop Inside Nscollectionview
How to Handle Async Requests in Swift
No Such Module Crashlytics - Pod Seems to Be Missing
How to Comprehend the "First-Class Function" in Swift
Swift Enum with Custom Initializer Loses Rawvalue Initializer
Secure Text .Echosbullets Not Working for Password Field
How to Call a Func Within a Closure
Swiftui How to Programatically Adjust Spacing Between Images and Text
Should I Remove All Skspritenodes and Labels When I Switch from One Node to Another
Raw Value of Enumeration, Default Value of a Class/Structure, What's the Different
Get Images from Document Directory Not File Path Swift 3
Swift Conforming Multiple Protocols Inherits from Same Protocol with Associated Type