Align text to the baseline and top of another text in SwiftUI
In this tutorial, we will see how to align text to the baseline and top of another text in SwiftUI.
I will create a custom speedometer view in SwiftUI. This view will display a large number in the center of the screen, a decimal point with a smaller text to the top of that number, and a unit indicator to the baseline.
Now, follow the steps below to achieve the task.
Large centered number
First of all, I will create a horizontal stack (HStack
) to organize our content horizontally. Inside this stack, I will create a Text
view that is the large number that will be displayed in the center of the screen.
Example
Text("7") .font(.system(size: 100)) .foregroundColor(.mint) .multilineTextAlignment(.center) .minimumScaleFactor(0.3)
In the above program, I have created a Text
view that would be displayed in the center of the screen and I made the text large with a size of 100.
Then, I have set the text color to mint using the .foregroundColor(.mint)
modifier and centered the text within its container using the .multilineTextAlignment(.center)
.
The minimumScaleFactor()
helps make sure that if the big number is too large to fit on the screen, it will shrink a bit so we can still easily read it.
Decimal point with a smaller text and unit indicator
Inside the same HStack
, I will create a vertical stack (VStack
) and two different Text
views inside it to display those views vertically.
Example
VStack(alignment: .leading, spacing: 9) { // Decimal point and small text Text(".7") .font(.system(size: 34)) .foregroundColor(.brown) // Unit (kts) text Text("kts") .font(.system(size: 28)) .foregroundColor(.red) }
In the above program, I have used a VStack
to arrange the elements vertically and align them to the leading edge.
The first Text
element will display the decimal point and the digit “7” with a smaller font size of 34.
Another Text
element will display the unit (“kts”) with a font size of 28 and a mint text color.
Now, have a look at the complete code below.
import SwiftUI struct ContentView: View { var body: some View { HStack(alignment: .lastTextBaseline, spacing: 3) { // Large centered number Text("7") .font(.system(size: 100)) .foregroundColor(.mint) .multilineTextAlignment(.center) .minimumScaleFactor(0.3) VStack(alignment: .leading, spacing: 9) { // Decimal point and small text Text(".7") .font(.system(size: 34)) .foregroundColor(.brown) // Unit (kts) text Text("kts") .font(.system(size: 28)) .foregroundColor(.red) } } } }
The above code will create a horizontal stack of a large number “7” and a vertical stack containing a smaller decimal point with the number “7” to the top of the large text, and the text kts
to the baseline of the large text.
Output:
Leave a Reply