— SwiftUI, Fonts, User Interface — 1 min read
When it comes to creating visually appealing and unique user interfaces, the choice of font plays a significant role. In SwiftUI, Apple's declarative framework for building user interfaces across all Apple platforms, incorporating custom fonts can enhance the overall aesthetics of an app. In this article, we will delve into the process of listing all available fonts in SwiftUI, along with practical examples to demonstrate their usage.
In SwiftUI, obtaining a list of available fonts is a straightforward process. By utilizing the UIFont
type, developers can easily retrieve a collection of available fonts. The UIFont
type provides access to system-defined font styles, as well as any custom fonts imported into the project. This capability allows for seamless integration of custom typography into the app's design.
Let's explore a simple example to illustrate how to display a list of available fonts using SwiftUI. Consider the following code snippet:
1import SwiftUI2
3struct FontList: View {4 var body: some View {5 List {6 ForEach(UIFont.familyNames, id: \.self) { family in7 Section(header: Text(family)) {8 ForEach(UIFont.fontNames(forFamilyName: family), id: \.self) { font in9 Text(font)10 .font(.custom(font, size: 20))11 }12 }13 }14 }15 }16}
In this example, a FontList
view is created to display a list of available fonts. By iterating through the font families and font names, the code generates a comprehensive display of the available pre-installed fonts. Here's what this should look like when you add it to your project and compile:
While system fonts offer a wide selection for use, incorporating custom fonts can elevate the visual appeal of an app's user interface. To integrate custom fonts in SwiftUI, developers can add font files to their Xcode project and declare them in the app's Info.plist. Once added, these custom fonts become accessible within the project, enabling developers to utilize them alongside system fonts.
Let's consider a scenario where a custom font named "MyCustomFont" is added to the Xcode project. To integrate this custom font in SwiftUI, the following code demonstrates its usage:
1import SwiftUI2
3struct CustomFontView: View {4 var body: some View {5 Text("Hello, Custom Font!")6 .font(.custom("MyCustomFont", size: 24))7 }8}
By invoking the .custom
method and specifying the name of the custom font, developers can seamlessly include the custom typography in their UI components, ensuring a cohesive and personalized design aesthetic. If you want a more indepth guide to this we have another post that you can check out here.