Reputation: 81
I'm making a small application to help kids to learn mathematics for kids.
However, I don't know how to write a fraction in SwiftUI ?
I would like something like this : 1⁄2
Thanks for your help :)
Upvotes: 3
Views: 832
Reputation: 257533
Now completely dynamic with font scaling supported, no layout hardcodes.
Main part:
ZStack {
Text("\(numerator) ")
.alignmentGuide(VerticalAlignment.center,
computeValue: { d in d[.bottom] })
.alignmentGuide(HorizontalAlignment.center,
computeValue: { d in d[.trailing] })
Text("\u{2215}").font(.system(size: scale))
Text(" \(denominator)")
.alignmentGuide(VerticalAlignment.center,
computeValue: { d in d[.top] })
.alignmentGuide(HorizontalAlignment.center,
computeValue: { d in d[.leading] })
}
Hope the following will be helpful. Of course you can tune parameters as you wish.
Demo:
Approach code:
import SwiftUI
struct FractionView: View {
var numerator: String
var denominator: String
var body: some View {
HStack {
Text("\(numerator)")
.offset(x: 4, y: 0)
.alignmentGuide(VerticalAlignment.center,
computeValue: { d in d[.bottom] })
Text("∕").font(.system(size: 32))
Text("\(denominator)")
.offset(x: -4, y: 0)
.alignmentGuide(VerticalAlignment.center,
computeValue: { d in d[.top] })
}
}
}
struct TestFraction: View {
var body: some View {
VStack(spacing: 8) {
FractionView(numerator: "1", denominator: "2")
FractionView(numerator: "5", denominator: "7")
FractionView(numerator: "11", denominator: "19")
FractionView(numerator: "31", denominator: "9")
}
}
}
struct TestFraction_Previews: PreviewProvider {
static var previews: some View {
TestFraction()
}
}
Upvotes: 2
Reputation: 1198
I recently came across an approach that might be more flexible than the currently proposed solution (not needing adaptation for different font sizes or styles).
Use the Unicode symbols for superscript and subscript numbers in combination with the Unicode fraction slash. A very simple solution could be:
Text("\u{2077}\u{2044}\u{2081}\u{2081}") // --> returns ⁷⁄₁₁
There is an interesting article that discusses this approach further: https://coderexmachina.medium.com/displaying-mathematical-fractions-in-swiftui-6a4dd625d842
Upvotes: 0