NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

How to format text inside text views

Paul Hudson    @twostraws   

Updated for Xcode 14.2

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 project

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 project

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 project

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 project

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 project

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

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

Hacking with Swift is sponsored by Essential Developer

SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.4/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.