BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

Tip - Use of extension to create Text Styles for a consistent look

Forums > SwiftUI

Most will probably know this anyway, however a few amongst the forum users may not know how effective the use of Extension for Text can be.

If you have many text strings in your app that have a style modifier applied, or you want to have a consistent look for the text strings across several apps that you are developing, then Extension can help you.

You can create a new Swift file - 'TextStyles.swift'


import SwiftUI

extension Text {

    func deepRedTextStyle() -> some View {
        self.foregroundColor(.red)
            .italic()
            .opacity(0.7)
            .font(.subheadline)
    }

    func captionTextStyle() -> some View {
        self.foregroundColor(.secondary)
            .font(.caption)
    }
}

// Then in the app you can use it as follows

Text("What is this?")
   .deepRedTextStyle()

Text("Great job!")
   .captionTextStyle()

Text("Thank you")
   .deepRedTextStyle()

Anything that you can add to Text as a modifier, can be used in the Extension definitions.

Not only will it make text appearance be consistent in your app, and between your apps, it will also save coding lines and make the code clearer and easier to follow.

5      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.