Skip to main content

How to combine text views together

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to combine text views together 관련

SwiftUI by Example

Back to Home

How to combine text views together | SwiftUI by Example

How to combine text views together

Updated for Xcode 15

SwiftUI’s text view overloads the + operator so that you can combine them together to make new text views.

This is helpful for times when you need to have different formatting across your views, because you can make each text view look exactly as you want then join them together to make a single combined text view. Even better, VoiceOver automatically recognizes them as a single piece of text when it comes to reading them out.

For example, this creates three text views then uses + to join them into a single text view to be returned:

Text("SwiftUI ")
    .font(.largeTitle)
+ Text("is ")
    .font(.headline)
+ Text("awesome")
    .font(.footnote)

Download this as an Xcode projectopen in new window

A line reading “SwiftUI is awesome” with “SwiftUI” in very large text and “is” in large text
A line reading “SwiftUI is awesome” with “SwiftUI” in very large text and “is” in large text

You can also use this technique to create different colors or font weights of text, like this:

Text("SwiftUI ")
    .foregroundStyle(.red)
+ Text("is ")
    .foregroundStyle(.orange)
    .fontWeight(.black)
+ Text("awesome")
    .foregroundStyle(.blue)

Download this as an Xcode projectopen in new window

A line reading “SwiftUI is awesome” with “SwiftUI” in red, “is” in bold orange, and “awesome” in blue
A line reading “SwiftUI is awesome” with “SwiftUI” in red, “is” in bold orange, and “awesome” in blue

Tips

Combining text views like this is as close as we get to attributed strings in SwiftUI – there is no support for using NSAttributedString at this time.

Similar solutions…
How to group views together | SwiftUI by Example

How to group views together
How to group views together with ControlGroup | SwiftUI by Example

How to group views together with ControlGroup
How to blend views together | SwiftUI by Example

How to blend views together
How to combine transitions | SwiftUI by Example

How to combine transitions
How to combine shapes to create new shapes | SwiftUI by Example

How to combine shapes to create new shapes

이찬희 (MarkiiimarK)
Never Stop Learning.