Quantumorange

Text with SwiftUI

Displaying text in SwiftUI is very easy, as you might expect:

Text("Hello World!!!")

You can use view modifiers to change the font and the color

  Text("Omnia disce")
            .font(.headline)
            .foregroundColor(Color.blue)

There are many other view modifiers available you can use include underline, bold , italic and strikethrough

Kerning controls the spacing between letters:

Text("Spaced Out")
            .kerning(10.0)

A nice feature of SwiftUI text views is that you can add them together:

  Text("Hello ").foregroundColor(Color.yellow) + Text("World!").foregroundColor(Color.red).bold()

If you want to use your own custom font, first you'll need to add the font to your app. There are 2 steps: First, add the font file to your project and make sure that it is a target member of your app. Then Register the font in you info.plist with the "Font Provided By Application" key.

See here for details.

You can now use you font like this:

Text("Swift UI ")
    .font(.custom("CartoonBlocksChristmas", size: 36))

Note that the name of the font may not be the name of the file. We can get all the font names like this:

     let fontNames = UIFont
             .familyNames
             .flatMap{ UIFont.fontNames(forFamilyName: $0) }
             .sorted()

Then we could print all the names out, or we can make a list to display all the fonts:

var body: some View {
    List {
        ForEach(fontNames.indices) { i in
                            Text(fontNames[i]).font(.custom(fontNames[i], size: 20))                    
        }
    }
}

Thats all I've got on Text for now.

Tagged with: