custom font property wrapper in swiftui in swift

To create a custom font property wrapper in SwiftUI, you can follow these steps:

  1. Create a new file and name it Font+.swift (or any name you prefer)
  2. Import the necessary modules:
main.swift
import SwiftUI
import UIKit
28 chars
3 lines
  1. Define the @propertyWrapper:
main.swift
@propertyWrapper
struct AppFont {
    private var font: Font
    
    init(wrappedValue: Font) {
        self.font = wrappedValue
    }
    
    var wrappedValue: Font {
        get { font }
        set {
            // We can customize the font here
            // For example, we can add some custom font name and update the font
            font = Font.custom("MyCustomFont", size: newValue.pointSize)
        }
    }
}
423 chars
18 lines
  1. In the above code, we created a @propertyWrapper called AppFont. The wrappedValue property returns the font object, and the init(wrappedValue:) initializer sets the font. Inside the set method, we can customize the font as desired.

  2. Now, you can use it like so:

main.swift
struct ContentView: View {
    @AppFont var titleFont = .headline
    
    var body: some View {
        Text("Hello, World!")
            .font(titleFont)
    }
}
164 chars
9 lines
  1. In the above code, we created an instance of AppFont called titleFont, which has a default font of .headline. We then use this titleFont in the font() modifier of the Text view.

  2. Now you can easily apply your custom font in any SwiftUI view and it automatically gets updated everywhere.

gistlibby LogSnag