Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 46 ยท Views and Layout

Text, Images and SF Symbols

Show text and pictures in SwiftUI: Text styling and formatting, Label, SF Symbols, asset catalog images, resizable images and AsyncImage for remote photos.

Text and images are the most common views in any app. They look simple, but they carry many details that matter in production: fonts that scale with the user's settings, symbols that match the surrounding text, images that fit different screens, and remote pictures that may be slow or missing. This lesson covers the views you will use every day: Text, Label, Image, SF Symbols and AsyncImage.

All SwiftUI blocks here are read-only because they need Xcode to render. Two runnable stand-ins model the formatting and fallback logic in plain Swift.

Four views for content

Text Styled, localized strings.
Label An icon and a title together.
Image Assets and SF Symbols.
AsyncImage Downloads a picture from a URL.
1 / 2

Text

Text displays one or more lines of read-only text. You style it with modifiers, and the styling follows the user's preferences:

Swift
Text("Welcome back")
    .font(.title2)
    .fontWeight(.semibold)
    .foregroundStyle(.secondary)
    .multilineTextAlignment(.center)
    .lineLimit(2)

Prefer semantic fonts such as .largeTitle, .title, .headline, .body, .callout, .footnote and .caption. They scale with the user's Dynamic Type setting. A fixed size like .font(.system(size: 14)) ignores that setting, which hurts people who need bigger text. If you need a custom size that still scales, use a text style as the base, for example .font(.title2.bold()).

By default text wraps onto as many lines as it needs. lineLimit(_:) caps the lines, truncationMode(_:) chooses where the ellipsis goes, and minimumScaleFactor(_:) lets text shrink a little before it truncates. Use shrinking sparingly because it makes small text even smaller.

Combining and formatting text

Text values can be concatenated, which is handy for mixed styles in one sentence:

Swift
Text("Total: ").foregroundStyle(.secondary)
    + Text("$24.50").bold()

String interpolation is the normal way to include data, but formatting should be done with format styles, not hand-made strings, because they respect the user's locale:

Swift
let price = 24.5
Text(price, format: .currency(code: "USD"))      // "$24.50" in en_US, "24,50 $" in fr_CA

let date = Date.now
Text(date, format: .dateTime.month().day())      // "Mar 4" or "4 mars", by locale
Text(date, style: .relative)                     // keeps updating: "3 min ago"

Text("Progress: \(0.62, format: .percent)")      // interpolation with a format

Hard-coding "$\(price)" shows the wrong separators and symbol for many users. The stand-in below does a simplified version: it formats a number with a fixed number of decimals and places the currency symbol, so you see why a single place for formatting beats scattered string building.

Swift Stand-in: one place for formatting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The real SwiftUI APIs go further: they pick separators, symbol position and even digit shapes from the user's region. Always prefer them in real apps.

Markdown and localization

A Text created from a string literal supports a small subset of Markdown and is also a localization key:

Swift
Text("Read the **terms** and *conditions*")   // bold and italic render
Text("Visit [our site](https://example.com)") // a tappable link

If you pass a String variable instead of a literal, SwiftUI shows it verbatim without Markdown or localization. Use Text(verbatim:) when you explicitly never want translation, such as for a user's name. Accessibility and Localization covers this further.

Label

A Label pairs a title with an icon, and the system decides how to show them depending on the context. In a List row or a toolbar, it shows both. In a compact toolbar it may show only the icon:

Swift
Label("Favorites", systemImage: "heart.fill")
Label("Settings", systemImage: "gearshape")
    .labelStyle(.titleAndIcon)

Prefer Label over an HStack of an Image and a Text. It aligns the icon with the text, it keeps the accessibility information together, and it adapts to menus, buttons and lists.

Image and SF Symbols

Image shows a picture. There are two main sources:

  1. SF Symbols, Apple's library of thousands of icons, referenced by name with Image(systemName:).
  2. Your assets, images in the asset catalog, referenced by name with Image("name").
Swift
Image(systemName: "star.fill")
    .font(.title)                 // symbols scale like text
    .foregroundStyle(.yellow)

Image(systemName: "wifi", variableValue: 0.6)   // a symbol with partial fill

Image("trail-photo")              // from Assets.xcassets
    .resizable()
    .scaledToFill()
    .frame(width: 200, height: 120)
    .clipped()

SF Symbols are vector shapes that behave like text: they use the font's size and weight, line up with adjacent Text, and have multiple rendering modes. You set the mode with symbolRenderingMode(_:) (.monochrome, .hierarchical, .palette, .multicolor) and the weight with fontWeight or symbolVariant, for example .symbolVariant(.fill). Symbol names are strings, so a typo gives a blank image and no compiler error. Browse the free SF Symbols app from Apple to find names and see which iOS version introduced each symbol.

Making bitmap images fit

A plain Image("photo") renders at its pixel size and does not shrink. To make it flexible, add .resizable() first, then choose a scaling mode:

  • .scaledToFit() keeps the whole image visible, possibly leaving empty space.
  • .scaledToFill() fills the frame and crops overflow; follow with .clipped().

The order matters: .resizable() must come before .frame and the scaling mode. View Modifiers and Their Order explains why. Always keep the aspect ratio; stretching a photo to an arbitrary size makes faces look wrong.

The asset catalog

Assets.xcassets stores images with the name you use in code. You can provide a 1x, 2x and 3x raster version, or a single vector PDF/SVG that Xcode scales. A name can also have a dark variant, and named colors work the same way. Because lookup is by name, a missing image shows nothing and logs a warning. The stand-in below shows a defensive pattern: ask for an image by name and fall back to a placeholder.

Swift Stand-in: asset lookup with a fallback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

In a real project a typo in an asset name just gives a blank image, which is easy to miss. Generated asset symbols (Xcode can create Image(.trailPhoto) style accessors for your catalog) turn those typos into compile errors, which is worth switching on.

AsyncImage

AsyncImage downloads an image from a URL and shows it when ready. Use the version with a phase closure to handle all three states:

Swift
AsyncImage(url: URL(string: "https://example.com/cover.jpg")) { phase in
    switch phase {
    case .empty:
        ProgressView()
    case .success(let image):
        image
            .resizable()
            .scaledToFill()
    case .failure:
        Image(systemName: "exclamationmark.triangle")
    @unknown default:
        EmptyView()
    }
}
.frame(width: 120, height: 120)
.clipShape(.rect(cornerRadius: 12))

AsyncImage is convenient but basic: it has no persistent cache control and no downsampling, so a long list of large remote photos can use lots of memory. For image-heavy screens, many apps use a dedicated image-loading layer. We return to this in Performance, Instruments and Smooth Scrolling.

Accessibility for images

Decorative images should be hidden from VoiceOver, and meaningful ones need a description:

Swift
Image("trail-photo")
    .accessibilityLabel("A hiker on a ridge at sunrise")

Image(systemName: "sparkles")
    .accessibilityHidden(true)       // purely decorative

SF Symbols used in a Label get their meaning from the label's title, so you rarely need to add more.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why prefer .font(.title2) over .font(.system(size: 22))?

    Semantic styles adapt to the user's preferred text size. A fixed point size ignores that setting.
  2. 2. Which pair is correct for making a photo from the asset catalog fill a 200 by 120 box without distortion?

    resizable() lets the image scale, scaledToFill() keeps the aspect ratio while filling, frame sets the box and clipped() cuts the overflow.
  3. 3. What happens if you mistype an SF Symbol name in Image(systemName:)?

    Symbol and asset names are strings, so a typo produces a blank image. Check names in the SF Symbols app.
  4. 4. When is it best to use Label instead of an HStack with an Image and a Text?

    Label groups icon and title as one unit, so alignment, accessibility and context-dependent styles are handled for you.
  5. 5. Which AsyncImage phase should show a progress indicator?

    While the download has not produced an image yet, the phase is .empty. Show a ProgressView there.

Summary

  • Use semantic fonts on Text so it scales with Dynamic Type, and format values with format styles, not hand-built strings.
  • String literals in Text support simple Markdown and act as localization keys; Text(verbatim:) skips both.
  • Label combines an icon and a title and adapts to its context.
  • SF Symbols behave like text; names are strings, so check them. Asset images need .resizable() and a scaling mode.
  • AsyncImage handles remote pictures with empty, success and failure phases but has limited caching.
  • Hide decorative images from VoiceOver and describe meaningful ones.

Next: View Modifiers and Their Order