Format text inside text view.

By | August 12, 2024

From iOS 13 onwards apple has introduced text formatting API named ‘Format’ and it is capable of showing dates, arrays and measurements and more.

If you use the .list() format type with an array of strings, you can get neatly formatted lists such as “Jay, Modi, and Webber”. For example, this will print ingredients lists correctly no matter how many items are added:

       var body: some View {
        VStack {
            Text(ingredients, format: .list(type: .and))
            
            Button("Add Ingredient") {
                let possibles = ["Bread", "Butter", "Bacon", "Barly"]
                
                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:

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

While 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.

  let length = Measurement(value: 300, unit: UnitLength.centimeters)

    var body: some View {
        Text(length, format: .measurement(width: .wide))
    }

For currency also there are API’s for formatting.

    var body: some View {
        Text(72.3, format: .currency(code: "CAD"))
    }

These are some of the most common utilities in apple garage. Hope you have enjoyed reading!

One thought on “Format text inside text view.

Leave a Reply

Your email address will not be published. Required fields are marked *