How to format text inside text views
How to format text inside text views êŽë š
Updated for Xcode 15
Updated in iOS 15
SwiftUI's text views are capable of showing dates, arrays, measurements and more, all through their format
parameter. However, this is available only in iOS 15, so for iOS 14 and 13 support please see the formatter
parameter below.
If you use the .list()
format type with an array of strings, you can get neatly formatted lists such as âHoward, Josie, and Kingsleyâ. For example, this will print ingredients lists correctly no matter how many items are added:
struct ContentView: View {
@State private var ingredients = [String]()
var body: some View {
VStack {
Text(ingredients, format: .list(type: .and))
Button("Add Ingredient") {
let possibles = ["Egg", "Sausage", "Bacon", "Spam"]
if let newIngredient = possibles.randomElement() {
ingredients.append(newIngredient)
}
}
}
}
}
If you have an array of a numeric type such as integers, you can format that by specifying a member style, like this:
struct ContentView: View {
@State private var rolls = [Int]()
var body: some View {
VStack {
Text(rolls, format: .list(memberStyle: .number, type: .and))
Button("Roll Dice") {
let result = Int.random(in: 1...6)
rolls.append(result)
}
}
}
}
Or if you're working with measurements such as distance or weight, the .measurement()
format type will automatically adjust your value for display in the user's locale. For example, if you were storing values in centimeters internally but the user had a US locale on their device, iOS will automatically display a value in feet or inches depending on the size of the value.
struct ContentView: View {
let length = Measurement(value: 225, unit: UnitLength.centimeters)
var body: some View {
Text(length, format: .measurement(width: .wide))
}
}
There's even a formatter for handling currencies correctly, ensuring that two decimal places are shown and also adding the currency symbol as appropriate:
Text(72.3, format: .currency(code: "CAD"))
If you need to support iOS 14 and 13, you can use the formatter
parameter instead â it still lets us customize the way data is presented inside the text, but it's not quite as easy to use.
For example, this defines a date formatter and uses it to make sure a task date is presented in human-readable form:
struct ContentView: View {
static let taskDateFormat: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .long
return formatter
}()
let dueDate = Date.now
var body: some View {
Text("Task due date: \(dueDate, formatter: Self.taskDateFormat)")
}
}
That will display something like âTask due date: February 4 2021â.
The text âTask due date: June 28, 2021â.