One Logo Pool Ball
SwiftUICore · IOS API REFERENCE

Text

struct · iOS 13.0+ · SDK 27.1

@frozen struct Text

A view that displays one or more lines of read-only text. A text view draws a string in your app's user interface using a ``Font/body`` font that's appropriate for the current platform. You can choose a different standard font, like ``Font/title`` or ``Font/caption``, using the ``View/font(_:)`` view modifier. Text("Hamlet") .font(.title) ![A text view showing the name "Hamlet" in a title font.](SwiftUI-Text-title.png) If you need finer control over the styling of the text, you can use the same modifier to configure a system font or choose a custom font. You can also apply view modifiers like ``Text/bold()`` or ``Text/italic()`` to further adjust the formatting. Text("by William Shakespeare") .font(.system(size: 12, weight: .light, design: .serif)) .italic() ![A text view showing by William Shakespeare in a 12 point, light, italic, serif font.](SwiftUI-Text-font.png) To apply styling within specific portions of the text, you can create the text view from an <doc://com.apple.documentation/documentation/Foundation/AttributedString>, which in turn allows you to use Markdown to style runs of text. You can mix string attributes and SwiftUI modifiers, with the string attributes taking priority. let attributedString = try! AttributedString( markdown: "_Hamlet_ by William Shakespeare") var body: some View { Text(attributedString) .font(.system(size: 12, weight: .light, design: .serif)) } ![A text view showing Hamlet by William Shakespeare in a 12 point, light, serif font, with the title Hamlet in italics.](SwiftUI-Text-attributed.png) A text view always uses exactly the amount of space it needs to display its rendered contents, but you can affect the view's layout. For example, you can use the ``View/frame(width:height:alignment:)`` modifier to propose specific dimensions to the view. If the view accepts the proposal but the text doesn't fit into the available space, the view uses a combination of wrapping, tightening, scaling, and truncation to make it fit. With a width of `100` points but no constraint on the height, a text view might wrap a long string: Text("To be, or not to be, that is the question:") .frame(width: 100) ![A text view showing a quote from Hamlet split over three lines.](SwiftUI-Text-split.png) Use modifiers like ``View/lineLimit(_:)``, ``View/allowsTightening(_:)``, ``View/minimumScaleFactor(_:)``, and ``View/truncationMode(_:)`` to configure how the view handles space constraints. For example, combining a fixed width and a line limit of `1` results in truncation for text that doesn't fit in that space: Text("Brevity is the soul of wit.") .frame(width: 100) .lineLimit(1) ![A text view showing a truncated quote from Hamlet starting Brevity is t and ending with three dots.](SwiftUI-Text-truncated.png) ### Localizing strings If you initialize a text view with a string literal, the view uses the ``Text/init(_:tableName:bundle:comment:)`` initializer, which interprets the string as a localization key and searches for the key in the table you specify, or in the default table if you don't specify one. Text("pencil") // Searches the default table in the main bundle. For an app localized in both English and Spanish, the above view displays "pencil" and "lápiz" for English and Spanish users, respectively. If the view can't perform localization, it displays the key instead. For example, if the same app lacks Danish localization, the view displays "pencil" for users in that locale. Similarly, an app that lacks any localization information displays "pencil" in any locale. To explicitly bypass localization for a string literal, use the ``Text/init(verbatim:)`` initializer. Text(verbatim: "pencil") // Displays the string "pencil" in any locale. If you initialize a text view with a variable value, the view uses the ``Text/init(_:)-9d1g4`` initializer, which doesn't localize the string. However, you can request localization by creating a ``LocalizedStringKey`` instance first, which triggers the ``Text/init(_:tableName:bundle:comment:)`` initializer instead: // Don't localize a string variable... Text(writingImplement) // ...unless you explicitly convert it to a localized string key. Text(LocalizedStringKey(writingImplement)) When localizing a string variable, you can use the default table by omitting the optional initialization parameters — as in the above example — just like you might for a string literal. When composing a complex string, where there is a need to assemble multiple pieces of text, use string interpolation: let name: String = //… Text("Hello, \(name)") This would look up the `"Hello, %@"` localization key in the localized string file and replace the format specifier `%@` with the value of `name` before rendering the text on screen. Using string interpolation ensures that the text in your app can be localized correctly in all locales, especially in right-to-left languages. If you desire to style only parts of interpolated text while ensuring that the content can still be localized correctly, interpolate `Text` or <doc://com.apple.documentation/documentation/Foundation/AttributedString>: let name = Text(person.name).bold() Text("Hello, \(name)") The example above uses ``LocalizedStringKey/StringInterpolation/appendInterpolation(_:)-4qyfo`` and will look up the `"Hello, %@"` in the localized string file and interpolate a bold text rendering the value of `name`. Using ``LocalizedStringKey/StringInterpolation/appendInterpolation(_:)-5m52e`` you can interpolate ``Image`` in text.

Members (38)

method · iOS 16.1+

fontDesign

TypeScript
fontDesign(design?: (Font_Design) | null): Text
Swift declaration
nonisolated func fontDesign(_ design: Font.Design?) -> Text

Sets the font design of the text. - Parameter design: One of the available font designs. - Returns: Text that uses the font design you specify.

method · iOS 13.0+

fontWeight

TypeScript
fontWeight(weight?: (Font_Weight) | null): Text
Swift declaration
nonisolated func fontWeight(_ weight: Font.Weight?) -> Text

Sets the font weight of the text. - Parameter weight: One of the available font weights. - Returns: Text that uses the font weight you specify.

method · iOS 16.4+

monospaced

TypeScript
monospaced(isActive?: boolean): Text
Swift declaration
nonisolated func monospaced(_ isActive: Bool = true) -> Text

Modifies the font of the text to use the fixed-width variant of the current font, if possible. - Parameter isActive: A Boolean value that indicates whether monospaced styling is added. Default value is `true`. - Returns: Monospaced text.

method · iOS 13.0+

strikethrough

TypeScript
strikethroughColor(isActive?: boolean, color?: (Color) | null): Text
Swift declaration
nonisolated func strikethrough(_ isActive: Bool = true, color: Color? = nil) -> Text

Applies a strikethrough to the text. - Parameters: - isActive: A Boolean value that indicates whether the text has a strikethrough applied. - color: The color of the strikethrough. If `color` is `nil`, the strikethrough uses the default foreground color. - Returns: Text with a line through its center.

method · iOS 16.0+

strikethrough

TypeScript
strikethroughPatternColor(isActive: boolean, pattern: Text_LineStyle_Pattern, color?: (Color) | null): Text
Swift declaration
nonisolated func strikethrough(_ isActive: Bool = true, pattern: Text.LineStyle.Pattern, color: Color? = nil) -> Text

Applies a strikethrough to the text. - Parameters: - isActive: A Boolean value that indicates whether strikethrough is added. The default value is `true`. - pattern: The pattern of the line. - color: The color of the strikethrough. If `color` is `nil`, the strikethrough uses the default foreground color. - Returns: Text with a line through its center.

init · iOS 16.0+

init

TypeScript
static initTimerIntervalPauseTimeCountsDownShowsHours(timerInterval: SDKHandle, pauseTime?: (globalThis.Date) | null, countsDown?: boolean, showsHours?: boolean): Text
Swift declaration
init(timerInterval: ClosedRange<Date>, pauseTime: Date? = nil, countsDown: Bool = true, showsHours: Bool = true)

Creates an instance that displays a timer counting within the provided interval. Text( timerInterval: Date.now...Date(timeInterval: 12 * 60, since: .now), pauseTime: Date.now + (10 * 60)) The example above shows a text that displays a timer counting down from "12:00" and will pause when reaching "10:00". - Parameters: - timerInterval: The interval between where to run the timer. - pauseTime: If present, the date at which to pause the timer. The default is `nil` which indicates to never pause. - countsDown: Whether to count up or down. The default is `true`. - showsHours: Whether to include an hours component if there are more than 60 minutes left on the timer. The default is `true`.

method · iOS 13.0+

baselineOffset

TypeScript
baselineOffset(baselineOffset: number): Text
Swift declaration
nonisolated func baselineOffset(_ baselineOffset: CGFloat) -> Text

Sets the vertical offset for the text relative to its baseline. Change the baseline offset to move the text in the view (in points) up or down relative to its baseline. The bounds of the view expand to contain the moved text. HStack(alignment: .top) { Text("Hello") .baselineOffset(-10) .border(Color.red) Text("Hello") .border(Color.green) Text("Hello") .baselineOffset(10) .border(Color.blue) } .background(Color(white: 0.9)) By drawing a border around each text view, you can see how the text moves, and how that affects the view. ![Three text views, each with the word "Hello" outlined by a border and aligned along the top edges. The first and last are larger than the second, with padding inside the border above the word "Hello" in the first case, and padding inside the border below the word in the last case.](SwiftUI-Text-baselineOffset.png) The first view, with a negative offset, grows downward to handle the lowered text. The last view, with a positive offset, grows upward. The enclosing ``HStack`` instance, shown in gray, ensures all the text views remain aligned at their top edge, regardless of the offset. - Parameter baselineOffset: The amount to shift the text vertically (up or down) relative to its baseline. - Returns: Text that's above or below its baseline.

method · iOS 13.0+ · Deprecated in iOS 100000.0

foregroundColor

TypeScript
foregroundColor(color?: (Color) | null): Text
Swift declaration
nonisolated func foregroundColor(_ color: Color?) -> Text

Sets the color of the text displayed by this view. Use this method to change the color of the text rendered by a text view. For example, you can display the names of the colors red, green, and blue in their respective colors: HStack { Text("Red").foregroundColor(.red) Text("Green").foregroundColor(.green) Text("Blue").foregroundColor(.blue) } ![Three text views arranged horizontally, each containing the name of a color displayed in that color.](SwiftUI-Text-foregroundColor.png) - Parameter color: The color to use when displaying this text. - Returns: A text view that uses the color value you supply.

method · iOS 17.0+

foregroundStyle

TypeScript
foregroundStyle(style: SDKHandle): Text
Swift declaration
nonisolated func foregroundStyle<S>(_ style: S) -> Text where S : ShapeStyle

Sets the style of the text displayed by this view. Use this method to change the rendering style of the text rendered by a text view. For example, you can display the names of the colors red, green, and blue in their respective colors: HStack { Text("Red").foregroundStyle(.red) Text("Green").foregroundStyle(.green) Text("Blue").foregroundStyle(.blue) } ![Three text views arranged horizontally, each containing the name of a color displayed in that color.](SwiftUI-Text-foregroundColor.png) - Parameter style: The style to use when displaying this text. - Returns: A text view that uses the color value you supply.

method · iOS 15.0+

monospacedDigit

TypeScript
monospacedDigit(): Text
Swift declaration
nonisolated func monospacedDigit() -> Text

Modifies the text view's font to use fixed-width digits, while leaving other characters proportionally spaced. This modifier only affects numeric characters, and leaves all other characters unchanged. The following example shows the effect of `monospacedDigit()` on a text view. It arranges two text views in a ``VStack``, each displaying a formatted date that contains many instances of the character 1. The second text view uses the `monospacedDigit()`. Because 1 is usually a narrow character in proportional fonts, applying the modifier widens all of the 1s, and the text view as a whole. The non-digit characters in the text view remain unaffected. let myDate = DateComponents( calendar: Calendar(identifier: .gregorian), timeZone: TimeZone(identifier: "EST"), year: 2011, month: 1, day: 11, hour: 11, minute: 11 ).date! var body: some View { VStack(alignment: .leading) { Text(myDate.formatted(date: .long, time: .complete)) .font(.system(size: 20)) Text(myDate.formatted(date: .long, time: .complete)) .font(.system(size: 20)) .monospacedDigit() } .padding() .navigationTitle("monospacedDigit() Modifier") } ![Two vertically stacked text views, displaying the date January 11, 2011, 11:11:00 AM. The second text view uses fixed-width digits, causing all of the 1s to be wider than in the first text view.](Text-monospacedDigit-1) If the base font of the text view doesn't support fixed-width digits, the font remains unchanged. - Returns: A text view with a modified font that uses fixed-width numeric characters, while leaving other characters proportionally spaced.

method · iOS 15.0+

speechAdjustedPitch

TypeScript
speechAdjustedPitch(value: number): Text
Swift declaration
func speechAdjustedPitch(_ value: Double) -> Text

Raises or lowers the pitch of spoken text. Use this modifier when you want to change the pitch of spoken text. The value indicates how much higher or lower to change the pitch. - Parameter value: The amount to raise or lower the pitch. Values between `-1` and `0` result in a lower pitch while values between `0` and `1` result in a higher pitch. The method clamps values to the range `-1` to `1`.

method · iOS 17.0+

typesettingLanguage

TypeScript
typesettingLanguageIsEnabled(language: _Foundation_Locale_Language, isEnabled?: boolean): Text
Swift declaration
func typesettingLanguage(_ language: Locale.Language, isEnabled: Bool = true) -> Text

Specifies the language for typesetting. In some cases `Text` may contain text of a particular language which doesn't match the device UI language. In that case it's useful to specify a language so line height, line breaking and spacing will respect the script used for that language. For example: Text(verbatim: "แอปเปิล") .typesettingLanguage(.init(languageCode: .thai)) Note: this language does not affect text localization. - Parameters: - language: The explicit language to use for typesetting. - isEnabled: A Boolean value that indicates whether text language is added - Returns: Text with the typesetting language set to the value you supply.

method · iOS 17.0+

typesettingLanguage

TypeScript
typesettingLanguageIsEnabled51448(language: TypesettingLanguage, isEnabled?: boolean): Text
Swift declaration
func typesettingLanguage(_ language: TypesettingLanguage, isEnabled: Bool = true) -> Text

Specifies the language for typesetting. In some cases `Text` may contain text of a particular language which doesn't match the device UI language. In that case it's useful to specify a language so line height, line breaking and spacing will respect the script used for that language. For example: Text(verbatim: "แอปเปิล").typesettingLanguage( .explicit(.init(languageCode: .thai))) Note: this language does not affect text localized localization. - Parameters: - language: The language to use for typesetting. - isEnabled: A Boolean value that indicates whether text language is added - Returns: Text with the typesetting language set to the value you supply.

method · iOS 15.0+

speechAnnouncementsQueued

TypeScript
speechAnnouncementsQueued(value?: boolean): Text
Swift declaration
func speechAnnouncementsQueued(_ value: Bool = true) -> Text

Controls whether to queue pending announcements behind existing speech rather than interrupting speech in progress. Use this modifier when you want affect the order in which the accessibility system delivers spoken text. Announcements can occur automatically when the label or value of an accessibility element changes. - Parameter value: A Boolean value that determines if VoiceOver speaks changes to text immediately or enqueues them behind existing speech. Defaults to `true`.

method · iOS 15.0+

speechSpellsOutCharacters

TypeScript
speechSpellsOutCharacters(value?: boolean): Text
Swift declaration
func speechSpellsOutCharacters(_ value: Bool = true) -> Text

Sets whether VoiceOver should speak the contents of the text view character by character. Use this modifier when you want VoiceOver to speak text as individual letters, character by character. This is important for text that is not meant to be spoken together, like: - An acronym that isn't a word, like APPL, spoken as "A-P-P-L". - A number representing a series of digits, like 25, spoken as "two-five" rather than "twenty-five". - Parameter value: A Boolean value that when `true` indicates VoiceOver should speak text as individual characters. Defaults to `true`.

method · iOS 15.0+

speechAlwaysIncludesPunctuation

TypeScript
speechAlwaysIncludesPunctuation(value?: boolean): Text
Swift declaration
func speechAlwaysIncludesPunctuation(_ value: Bool = true) -> Text

Sets whether VoiceOver should always speak all punctuation in the text view. Use this modifier to control whether the system speaks punctuation characters in the text. You might use this for code or other text where the punctuation is relevant, or where you want VoiceOver to speak a verbatim transcription of the text you provide. For example, given the text: Text("All the world's a stage, " + "And all the men and women merely players;") .speechAlwaysIncludesPunctuation() VoiceOver would speak "All the world apostrophe s a stage comma and all the men and women merely players semicolon". By default, VoiceOver voices punctuation based on surrounding context. - Parameter value: A Boolean value that you set to `true` if VoiceOver should speak all punctuation in the text. Defaults to `true`.

method · iOS 13.0+

bold

TypeScript
bold(): Text
Swift declaration
nonisolated func bold() -> Text

Applies a bold or emphasized treatment to the fonts of the text. For fonts created from text styles, it could mean applying emphasized styling, which does not necessarily mean the bold weight specifically, so this modifier is not to be confused with <doc://com.apple.documentation/documentation/SwiftUI/Text/fontWeight(_:)>. For example: Text("hello").font(.body).bold() will most likely get you the emphasized version of body text style, which is often in <doc://com.apple.documentation/documentation/SwiftUI/Font/weight/semibold> weight. While Text("hello").font(.body).fontWeight(.bold) will specifically get you the body text style font in the <doc://com.apple.documentation/documentation/SwiftUI/Font/weight/bold> weight. - Returns: Bold or emphasized text.

method · iOS 16.0+

bold

TypeScript
bold33576(isActive: boolean): Text
Swift declaration
nonisolated func bold(_ isActive: Bool) -> Text

Applies a bold font weight to the text. - Parameter isActive: A Boolean value that indicates whether text has bold styling. - Returns: Bold text.

method · iOS 13.0+

font

TypeScript
font(font?: (Font) | null): Text
Swift declaration
nonisolated func font(_ font: Font?) -> Text

Sets the default font for text in the view. Use `font(_:)` to apply a specific font to an individual Text View, or all of the text views in a container. In the example below, the first text field has a font set directly, while the font applied to the following container applies to all of the text views inside that container: VStack { Text("Font applied to a text view.") .font(.largeTitle) VStack { Text("These two text views have the same font") Text("applied to their parent view.") } .font(.system(size: 16, weight: .light, design: .default)) } ![Applying a font to a single text view or a view container](SwiftUI-view-font.png) - Parameter font: The font to use when displaying this text. - Returns: Text that uses the font you specify.

method · iOS 13.0+

italic

TypeScript
italic(): Text
Swift declaration
nonisolated func italic() -> Text

Applies italics to the text. - Returns: Italic text.

method · iOS 16.0+

italic

TypeScript
italic41109(isActive: boolean): Text
Swift declaration
nonisolated func italic(_ isActive: Bool) -> Text

Applies italics to the text. - Parameter isActive: A Boolean value that indicates whether italic styling is added. - Returns: Italic text.

method · iOS 13.0+

kerning

TypeScript
kerning(kerning: number): Text
Swift declaration
nonisolated func kerning(_ kerning: CGFloat) -> Text

Sets the spacing, or kerning, between characters. Kerning defines the offset, in points, that a text view should shift characters from the default spacing. Use positive kerning to widen the spacing between characters. Use negative kerning to tighten the spacing between characters. VStack(alignment: .leading) { Text("ABCDEF").kerning(-3) Text("ABCDEF") Text("ABCDEF").kerning(3) } The last character in the first case, which uses negative kerning, experiences cropping because the kerning affects the trailing edge of the text view as well. ![Three text views showing character groups, with progressively increasing spacing between the characters in each group.](SwiftUI-Text-kerning-1.png) Kerning attempts to maintain ligatures. For example, the Hoefler Text font uses a ligature for the letter combination _ffl_, as in the word _raffle_, shown here with a small negative and a small positive kerning: ![Two text views showing the word raffle in the Hoefler Text font, the first with small negative and the second with small positive kerning. The letter combination ffl has the same shape in both variants because it acts as a ligature.](SwiftUI-Text-kerning-2.png) The *ffl* letter combination keeps a constant shape as the other letters move together or apart. Beyond a certain point in either direction, however, kerning does disable nonessential ligatures. ![Two text views showing the word raffle in the Hoefler Text font, the first with large negative and the second with large positive kerning. The letter combination ffl does not act as a ligature in either case.](SwiftUI-Text-kerning-3.png) - Important: If you add both the ``Text/tracking(_:)`` and ``Text/kerning(_:)`` modifiers to a view, the view applies the tracking and ignores the kerning. - Parameter kerning: The spacing to use between individual characters in this text. Value of `0` sets the kerning to the system default value. - Returns: Text with the specified amount of kerning.

method · iOS 13.0+

tracking

TypeScript
tracking(tracking: number): Text
Swift declaration
nonisolated func tracking(_ tracking: CGFloat) -> Text

Sets the tracking for the text. Tracking adds space, measured in points, between the characters in the text view. A positive value increases the spacing between characters, while a negative value brings the characters closer together. VStack(alignment: .leading) { Text("ABCDEF").tracking(-3) Text("ABCDEF") Text("ABCDEF").tracking(3) } The code above uses an unusually large amount of tracking to make it easy to see the effect. ![Three text views showing character groups with progressively increasing spacing between the characters in each group.](SwiftUI-Text-tracking.png) The effect of tracking resembles that of the ``Text/kerning(_:)`` modifier, but adds or removes trailing whitespace, rather than changing character offsets. Also, using any nonzero amount of tracking disables nonessential ligatures, whereas kerning attempts to maintain ligatures. - Important: If you add both the ``Text/tracking(_:)`` and ``Text/kerning(_:)`` modifiers to a view, the view applies the tracking and ignores the kerning. - Parameter tracking: The amount of additional space, in points, that the view should add to each character cluster after layout. Value of `0` sets the tracking to the system default value. - Returns: Text with the specified amount of tracking.

init · iOS 13.0+

init

TypeScript
static initVerbatim(content: string): Text
Swift declaration
init(verbatim content: String)

Creates a text view that displays a string literal without localization. Use this initializer to create a text view with a string literal without performing localization: Text(verbatim: "pencil") // Displays the string "pencil" in any locale. If you want to localize a string literal before displaying it, use the ``Text/init(_:tableName:bundle:comment:)`` initializer instead. If you want to display a string variable, use the ``Text/init(_:)-9d1g4`` initializer, which also bypasses localization. - Parameter content: A string to display without localization.

method · iOS 16.0+

fontWidth

TypeScript
fontWidth(width?: (Font_Width) | null): Text
Swift declaration
nonisolated func fontWidth(_ width: Font.Width?) -> Text

Sets the font width of the text. - Parameter width: One of the available font widths. - Returns: Text that uses the font width you specify, if available.

method · iOS 17.0+

textScale

TypeScript
textScale(scale: Text_Scale, isEnabled?: boolean): Text
Swift declaration
func textScale(_ scale: Text.Scale, isEnabled: Bool = true) -> Text

Applies a text scale to the text. - Parameters: - scale: The text scale to apply. - isEnabled: If true the text scale is applied; otherwise text scale is unchanged. - Returns: Text with the specified scale applied.

method · iOS 13.0+

underline

TypeScript
underlineColor(isActive?: boolean, color?: (Color) | null): Text
Swift declaration
nonisolated func underline(_ isActive: Bool = true, color: Color? = nil) -> Text

Applies an underline to the text. - Parameters: - isActive: A Boolean value that indicates whether the text has an underline. - color: The color of the underline. If `color` is `nil`, the underline uses the default foreground color. - Returns: Text with a line running along its baseline.

method · iOS 16.0+

underline

TypeScript
underlinePatternColor(isActive: boolean, pattern: Text_LineStyle_Pattern, color?: (Color) | null): Text
Swift declaration
nonisolated func underline(_ isActive: Bool = true, pattern: Text.LineStyle.Pattern, color: Color? = nil) -> Text

Applies an underline to the text. - Parameters: - isActive: A Boolean value that indicates whether underline styling is added. The default value is `true`. - pattern: The pattern of the line. - color: The color of the underline. If `color` is `nil`, the underline uses the default foreground color. - Returns: Text with a line running along its baseline.

init · iOS 14.0+

init

TypeScript
static initStyle(date: globalThis.Date, style: Text_DateStyle): Text
Swift declaration
init(_ date: Date, style: Text.DateStyle)

Creates an instance that displays localized dates and times using a specific style. - Parameters: - date: The target date to display. - style: The style used when displaying a date.

init · iOS 14.0+

init

TypeScript
static initFormatter(subject: ArrayBuffer, formatter: _Foundation_Formatter): Text
Swift declaration
init<Subject>(_ subject: Subject, formatter: Formatter) where Subject : ReferenceConvertible

Creates a text view that displays the formatted representation of a reference-convertible value. Use this initializer to create a text view that formats `subject` using `formatter`. - Parameters: - subject: A <doc://com.apple.documentation/documentation/Foundation/ReferenceConvertible> instance compatible with `formatter`. - formatter: A <doc://com.apple.documentation/documentation/Foundation/Formatter> capable of converting `subject` into a string representation.

init · iOS 14.0+

init

TypeScript
static initFormatter95052(subject: _ObjectiveC_NSObject, formatter: _Foundation_Formatter): Text
Swift declaration
init<Subject>(_ subject: Subject, formatter: Formatter) where Subject : NSObject

Creates a text view that displays the formatted representation of a Foundation object. Use this initializer to create a text view that formats `subject` using `formatter`. - Parameters: - subject: An <doc://com.apple.documentation/documentation/ObjectiveC/NSObject-swift.class> instance compatible with `formatter`. - formatter: A <doc://com.apple.documentation/documentation/Foundation/Formatter> capable of converting `subject` into a string representation.

init · iOS 13.0+

init

TypeScript
static initTableNameBundleComment(key: LocalizedStringKey, tableName?: (string) | null, bundle?: (_Foundation_Bundle) | null, comment?: (SDKHandle) | null): Text
Swift declaration
init(_ key: LocalizedStringKey, tableName: String? = nil, bundle: Bundle? = nil, comment: StaticString? = nil)

Creates a text view that displays localized content identified by a key. Use this initializer to look for the `key` parameter in a localization table and display the associated string value in the initialized text view. If the initializer can't find the key in the table, or if no table exists, the text view displays the string representation of the key instead. Text("pencil") // Localizes the key if possible, or displays "pencil" if not. When you initialize a text view with a string literal, the view triggers this initializer because it assumes you want the string localized, even when you don't explicitly specify a table, as in the above example. If you haven't provided localization for a particular string, you still get reasonable behavior, because the initializer displays the key, which typically contains the unlocalized string. If you initialize a text view with a string variable rather than a string literal, the view triggers the ``Text/init(_:)-9d1g4`` initializer instead, because it assumes that you don't want localization in that case. If you do want to localize the value stored in a string variable, you can choose to call the `init(_:tableName:bundle:comment:)` initializer by first creating a ``LocalizedStringKey`` instance from the string variable: Text(LocalizedStringKey(someString)) // Localizes the contents of `someString`. If you have a string literal that you don't want to localize, use the ``Text/init(verbatim:)`` initializer instead. ### Styling localized strings with markdown If the localized string or the fallback key contains Markdown, the view displays the text with appropriate styling. For example, consider an app with the following entry in its Spanish localization file: "_Please visit our [website](https://www.example.com)._" = "_Visita nuestro [sitio web](https://www.example.com)._"; You can create a `Text` view with the Markdown-formatted base language version of the string as the localization key, like this: Text("_Please visit our [website](https://www.example.com)._") When viewed in a Spanish locale, the view uses the Spanish text from the strings file, applying the Markdown styling. ![A text view that says Visita nuestro sitio web, with all text displayed in italics. The words sitio web are colored blue to indicate they are a link.](SwiftUI-Text-init-localized.png) > Important: `Text` doesn't render all styling possible in Markdown. It doesn't support line breaks, soft breaks, or any style of paragraph- or block-based formatting like lists, block quotes, code blocks, or tables. It also doesn't support the <doc://com.apple.documentation/documentation/Foundation/AttributeScopes/FoundationAttributes/imageURL> attribute. Parsing with SwiftUI treats any whitespace in the Markdown string as described by the <doc://com.apple.documentation/documentation/Foundation/AttributedString/MarkdownParsingOptions/InterpretedSyntax-swift.enum/inlineOnlyPreservingWhitespace> parsing option. - Parameters: - key: The key for a string in the table identified by `tableName`. - tableName: The name of the string table to search. If `nil`, use the table in the `Localizable.strings` file. - bundle: The bundle containing the strings file. If `nil`, use the main bundle. - comment: Contextual information about this key-value pair.

init · iOS 14.0+

init

TypeScript
static init(interval: _Foundation_DateInterval): Text
Swift declaration
init(_ interval: DateInterval)

Creates an instance that displays a localized time interval. Text(DateInterval(start: event.startDate, duration: event.duration)) Example output: 9:30AM - 3:30PM - Parameters: - interval: The date interval to display

init · iOS 15.0+

init

TypeScript
static init22014(attributedContent: _Foundation_AttributedString): Text
Swift declaration
init(_ attributedContent: AttributedString)

Creates a text view that displays styled attributed content. ### Format text by combining attributes and view modifiers Use this initializer to style text according to attributes found in the specified <doc://com.apple.documentation/documentation/Foundation/AttributedString>. Attributes in the attributed string take precedence over styles added by view modifiers. For example, the attributed text in the following example appears in blue, despite the use of the ``View/foregroundColor(_:)`` modifier to use red throughout the enclosing ``VStack``: var content: AttributedString { var attributedString = AttributedString("Blue text") attributedString.foregroundColor = .blue return attributedString } var body: some View { VStack { Text(content) Text("Red text") } .foregroundColor(.red) } ![A vertical stack of two text views, the top labeled Blue Text with a blue font color, and the bottom labeled Red Text with a red font color.](SwiftUI-Text-init-attributed.png) SwiftUI combines text attributes with SwiftUI modifiers whenever possible. For example, the following listing creates text that is both bold and red: var content: AttributedString { var content = AttributedString("Some text") content.inlinePresentationIntent = .stronglyEmphasized return content } var body: some View { Text(content).foregroundColor(Color.red) } ### Supported Foundation attributes A SwiftUI ``Text`` view renders most of the styles defined by the Foundation attribute <doc://com.apple.documentation/documentation/Foundation/AttributeScopes/FoundationAttributes/inlinePresentationIntent>, like the <doc://com.apple.documentation/documentation/Foundation/InlinePresentationIntent/stronglyEmphasized> value, which SwiftUI presents as bold text. > Important: ``Text`` uses only a subset of the attributes defined in <doc://com.apple.documentation/documentation/Foundation/AttributeScopes/FoundationAttributes>. `Text` renders all <doc://com.apple.documentation/documentation/Foundation/InlinePresentationIntent> attributes except for <doc://com.apple.documentation/documentation/Foundation/InlinePresentationIntent/lineBreak> and <doc://com.apple.documentation/documentation/Foundation/InlinePresentationIntent/softBreak>. It also respects <doc://com.apple.documentation/documentation/Foundation/AttributeScopes/FoundationAttributes/writingDirection> and renders the <doc://com.apple.documentation/documentation/Foundation/AttributeScopes/FoundationAttributes/link> attribute as a clickable link. `Text` ignores any other Foundation-defined attributes in an attributed string. ### SwiftUI attributes SwiftUI also defines additional attributes in the attribute scope <doc://com.apple.documentation/documentation/Foundation/AttributeScopes/SwiftUIAttributes> which you can access from an attributed string's <doc://com.apple.documentation/documentation/Foundation/AttributeScopes/swiftUI> property. SwiftUI attributes take precedence over equivalent attributes from other frameworks, such as <doc://com.apple.documentation/documentation/Foundation/AttributeScopes/UIKitAttributes> and <doc://com.apple.documentation/documentation/Foundation/AttributeScopes/AppKitAttributes>. ### Markdown support You can create an `AttributedString` with Markdown syntax, which allows you to style distinct runs within a `Text` view: let content = try! AttributedString( markdown: "**Thank You!** Please visit our [website](http://example.com).") var body: some View { Text(content) } The `**` syntax around "Thank You!" applies an <doc://com.apple.documentation/documentation/Foundation/AttributeScopes/FoundationAttributes/inlinePresentationIntent> attribute with the value <doc://com.apple.documentation/documentation/Foundation/InlinePresentationIntent/stronglyEmphasized>. SwiftUI renders this as bold text, as described earlier. The link syntax around "website" creates a <doc://com.apple.documentation/documentation/Foundation/AttributeScopes/FoundationAttributes/link> attribute, which `Text` styles to indicate it's a link; by default, clicking or tapping the link opens the linked URL in the user's default browser. Alternatively, you can perform custom link handling by putting an ``OpenURLAction`` in the text view's environment. ![A text view that says Thank you. Please visit our website. The text The view displays the words Thank you in a bold font, and the word website styled to indicate it is a link.](SwiftUI-Text-init-markdown.png) You can also use Markdown syntax in localized string keys, which means you can write the above example without needing to explicitly create an `AttributedString`: var body: some View { Text("**Thank You!** Please visit our [website](https://example.com).") } In your app's strings files, use Markdown syntax to apply styling to the app's localized strings. You also use this approach when you want to perform automatic grammar agreement on localized strings, with the `^[text](inflect:true)` syntax. For details about Markdown syntax support in SwiftUI, see ``Text/init(_:tableName:bundle:comment:)``. ### Applying a custom text formatting definition Use the ``View/attributedTextFormattingDefinition(_:)-(D)`` modifier to apply a custom ``AttributedTextFormattingDefinition`` to text created using this initializer. This will result in the text only applying attributes in the definition's attribute scope and constraining attributes according to the definition's value constraints prior to display. Custom attributes listed in the definition's ``AttributedTextFormattingDefinition/Scope``, where the <doc://com.apple.documentation/documentation/Foundation/AttributedStringKey/Value> conforms to the ``TextAttribute`` protocol, can be read when observing the text's layout using ``Text/Layout/Run/subscript(key:)->T?``, just as text attributes applied using the ``Text/customAttribute(_:)`` modifier. - Parameters: - attributedContent: An attributed string to style and display, in accordance with its attributes.

init · iOS 16.0+

init

TypeScript
static init16285(resource: _Foundation_LocalizedStringResource): Text
Swift declaration
init(_ resource: LocalizedStringResource)

Creates a text view that displays a localized string resource. Use this initializer to display a localized string that is represented by a <doc://com.apple.documentation/documentation/Foundation/LocalizedStringResource> var object = LocalizedStringResource("pencil") Text(object) // Localizes the resource if possible, or displays "pencil" if not.

init · iOS 14.0+

init

TypeScript
static init59775(dates: SDKHandle): Text
Swift declaration
init(_ dates: ClosedRange<Date>)

Creates an instance that displays a localized range between two dates. - Parameters: - dates: The range of dates to display

init · iOS 13.0+

init

TypeScript
static init2201(content: string): Text
Swift declaration
init<S>(_ content: S) where S : StringProtocol

Creates a text view that displays a stored string without localization. Use this initializer to create a text view that displays — without localization — the text in a string variable. Text(someString) // Displays the contents of `someString` without localization. SwiftUI doesn't call the `init(_:)` method when you initialize a text view with a string literal as the input. Instead, a string literal triggers the ``Text/init(_:tableName:bundle:comment:)`` method — which treats the input as a ``LocalizedStringKey`` instance — and attempts to perform localization. By default, SwiftUI assumes that you don't want to localize stored strings, but if you do, you can first create a localized string key from the value, and initialize the text view with that. Using a key as input triggers the ``Text/init(_:tableName:bundle:comment:)`` method instead. - Parameter content: The string value to display without localization.

init · iOS 14.0+

init

TypeScript
static init43831(image: Image): Text
Swift declaration
init(_ image: Image)

Creates an instance that wraps an `Image`, suitable for concatenating with other `Text`

Skipped declarations

6 declarations were excluded from these bindings. Each reason comes from the generator or the iOS SDK compiler.

Text.textVariant(_:)

This declaration needs Swift generic type arguments. (no canonical witness for V)

Text.init(_:format:)

This declaration needs Swift generic type arguments. (no canonical witness for F)

Text.init(_:format:)

This declaration needs Swift generic type arguments. (no canonical witness for F)

Text.customAttribute(_:)

This declaration needs Swift generic type arguments. (no canonical witness for T)

Text.init(_:format:)

This declaration needs Swift generic type arguments. (no canonical witness for F)

Text.init(_:format:)

This declaration needs Swift generic type arguments. (no canonical witness for F)

All SwiftUICore types →