Skip to main content

How to format text inside text views

About 3 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to format text inside text views 관련

SwiftUI by Example

Back to Home

How to format text inside text views | SwiftUI by Example

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)
                }
            }
        }
    }
}

Download this as an Xcode projectopen in new window

The words “Spam, Egg, Sausage, and Bacon” above an “” button.
The words “Spam, Egg, Sausage, and Bacon” above an “[Add Ingredient]” button.

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)
            }
        }
    }
}

Download this as an Xcode projectopen in new window

The line “4, 3, 2, and 6” above a “Roll Dice” button.
The line “4, 3, 2, and 6” above a “Roll Dice” button.

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))
    }
}

Download this as an Xcode projectopen in new window

The text “7.4 feet”.
The text “7.4 feet”.

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"))

Download this as an Xcode projectopen in new window

The text “CA$72.30”.
The text “CA$72.30”.

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)")
    }
}

Download this as an Xcode projectopen in new window

That will display something like “Task due date: February 4 2021”.

The text “Task due date: June 28, 2021”.

Similar solutions…
How to format dates inside text views | SwiftUI by Example

How to format dates inside text views
How to format a TextField for numbers | SwiftUI by Example

How to format a TextField for numbers
How to force views to one side inside a stack using Spacer | SwiftUI by Example

How to force views to one side inside a stack using Spacer
How to disable the overlay color for images inside Button and NavigationLink | SwiftUI by Example

How to disable the overlay color for images inside Button and NavigationLink
How to draw a border inside a view | SwiftUI by Example

How to draw a border inside a view

이찬희 (MarkiiimarK)
Never Stop Learning.