UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

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.