init(text:selection:)
Creates a styled text editor.
Declaration
init(text: Binding<AttributedString>, selection: Binding<AttributedTextSelection>? = nil)Parameters
Discussion
Use a TextEditor instance to create a view in which users can enter and edit long-form styled text.
In this example the text editor is setup to edit styled text:
struct StyledTextEditingView: View {
@State private var text =
AttributedString("This is some editable text...")
var body: some View {
TextEditor(text: $text)
}
}Format text by combining attributes and view modifiers
If the AttributedString does not have a font and/or foreground color specified for a given range of text, the rich text editor will use the font and/or foreground color inherited from the environment for that range of text, just like init(_:). To control what formatting options are available in the editor, use the AttributedTextFormattingDefinition protocol.
Build custom controls using the selection binding
Use AttributedTextSelection for implementing custom controls, e.g. for applying formatting such as boldness:
struct StyledTextEditingView: View {
@State private var text: AttributedString = ""
@State private var selection = AttributedTextSelection()
@Environment(\.fontResolutionContext) private var fontResolutionContext
var body: some View {
TextEditor(text: $text, selection: $selection)
.toolbar {
// A toggle controlling whether the current selection in the
// editor has bold font.
Toggle(
"Toggle Boldness",
systemImage: "bold",
isOn: Binding(get: {
// Get the font for the current selection.
let font = selection.typingAttributes(in: text).font
// Resolve the font in the current environment.
let resolved = (font ?? .default).resolve(in: fontResolutionContext)
// Return whether the resolved font is bold.
return resolved.isBold
}, set: { isBold in
// Update each run in the current selection, including
// the typing attributes, to reflect the new `isBold`
// value.
text.transformAttributes(in: &selection) {
// Override the boldness of the font. If no font is
// present, use `Font.default` for the effective
// environment font as the basis.
$0.font = ($0.font ?? .default).bold(isBold)
}
})
)
}
}
}