SwiftUI Text — things you can do
2 min readApr 9, 2024
Explore the versatile capabilities of SwiftUI’s Text view, from basic formatting to advanced styling, localization, and dynamic content rendering.
Dynamic Size
Text("Hello World")
.font(.title)
Text("Hello World")
.font(.title)
.lineLimit(1)
.minimumScaleFactor(0.5)
.frame(width: 70)
Concatenation
Text("Hello").font(.title) + Text(" World").font(.subheadline)
Localization
// use of this overloaded init
Text.init(
_ key: LocalizedStringKey,
tableName: String? = nil,
bundle: Bundle? = nil,
comment: StaticString? = nil
)
Text("Visit my [website](https://www.apple.com)")
let key: LocalizedStringKey = "Visit my [website](https://www.apple.com)"
Text(key)
Text("This is normal text")
Text("This is **bold** text, this is *italic* text, this is ***bold, italic*** text.")
Text("~~strikethrough~~")
Text("`monospaced`")
Link color
Text("Visit my [website](https://www.apple.com)")
.tint(.red)
Link click detection
Text("Visit my [website](https://www.apple.com)")
.environment(\.openURL, OpenURLAction { url in
print("clicked \(url)")
return .handled
})
Inline Text replacement
Text("This is \(Text("red").foregroundColor(.red).bold()) text")
// all the methods those returns Text are supported
// custom types need to conform LocalizedStringKey.StringInterpolation
Auto update Dates
let date = Date(timeIntervalSinceNow: 60*60)
let now = Date()
var body: some View {
VStack {
Text("Date \(now, style: .date)")
Text("Time \(now, style: .time)")
Text("Time left \(date, style: .relative)")
Text("Timer \(date, style: .timer)")
Text("Time passed \(now, style: .offset)")
}
.monospacedDigit()
.frame(width: 300)
.padding(40)
}
Comment if you have something interesting about SwiftUI Texts.
Thanks for reading.