FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

How to provide visual structure using foreground styles

Paul Hudson    @twostraws   

Updated for Xcode 13.0 beta 5

New in iOS 15

SwiftUI provides a foregroundStyle() modifier to control the way text, images, and shapes are styled all at once. In its simplest form this is similar to using foregroundColor() with .secondary, but not only does it unlock more of the semantic colors – .tertiary and .quaternary, it also adds support for anything that conforms to ShapeStyle.

So, here’s an example of an image and some text rendered using quaternary style, which is the lowest of four importance levels for content:

HStack {
    Image(systemName: "clock.fill")
    Text("Set the time")
}
.font(.largeTitle.bold())
.foregroundStyle(.quaternary)

Download this as an Xcode project

A clock symbol beside the words “Set the time”, both in faint grey.

Like I said, anything that conforms to ShapeStyle also works, meaning that we can render our HStack with a red to black linear gradient using the same modifier:

HStack {
    Image(systemName: "clock.fill")
    Text("Set the time")
}
.font(.largeTitle.bold())
.foregroundStyle(
    .linearGradient(
        colors: [.red, .black],
        startPoint: .top,
        endPoint: .bottom
    )
)

Download this as an Xcode project

A clock symbol beside the words “Set the time”, both with a gradient running from red at the top to black at the bottom.

Hacking with Swift is sponsored by Raycast

SPONSORED Get stuff done faster with Raycast. The Mac app combines the Spotlight experience with third-party services. Create issues in Jira, search pull requests on GitHub, join video calls in Zoom and more. It's accessible via keyboard shortcuts and extendable with scripts. Built for macOS with Swift.

Download for free

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

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift 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 (Vapor Edition) 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 Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.