1# Text
2
3The **Text** component is used to display a piece of textual information.
4
5>  **NOTE**
6>
7>  This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
8
9
10## Child Components
11
12This component can contain the [Span](ts-basic-components-span.md), [ImageSpan](ts-basic-components-imagespan.md), [SymbolSpan](ts-basic-components-symbolSpan.md), and [ContainerSpan](ts-basic-components-containerspan.md) child components.
13
14## APIs
15
16Text(content?: string | Resource , value?: TextOptions)
17
18**Widget capability**: This API can be used in ArkTS widgets since API version 9.
19
20**Atomic service API**: This API can be used in atomic services since API version 11.
21
22**System capability**: SystemCapability.ArkUI.ArkUI.Full
23
24**Parameters**
25
26| Name| Type| Mandatory| Description|
27| -------- | -------- | -------- | -------- |
28| content | string \| [Resource](ts-types.md#resource) | No| Text content. This parameter does not take effect if the component contains a **\<Span>** child component and does not have any [styled string](ts-universal-styled-string.md#styled-string) configured. In this case, the span content is displayed, and the style of the component does not take effect.<br>Default value: **' '**|
29| value<sup>11+</sup> | [TextOptions](#textoptions11) | No| Initialization options of the component.|
30
31## Attributes
32
33In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
34
35### textAlign
36
37textAlign(value: TextAlign)
38
39Sets the horizontal alignment mode of the text.
40
41The text takes up the full width of the **Text** component.
42
43To set vertical alignment for the text, use the [align](ts-universal-attributes-location.md) attribute. The **align** attribute alone does not control the horizontal position of the text. In other words, **Alignment.TopStart**, **Alignment.Top**, and **Alignment.TopEnd** produce the same effect, top-aligning the text; **Alignment.Start**, **Alignment.Center**, and **Alignment.End** produce the same effect, centered-aligning the text vertically; **Alignment.BottomStart**, **Alignment.Bottom**, and **Alignment.BottomEnd** produce the same effect, bottom-aligning the text. Yet, it can work with the **textAlign** attribute to jointly determine the horizontal position of the text.
44
45When **textAlign** is set to **TextAlign.JUSTIFY**, you must set the [wordBreak](#wordbreak11) attribute, and the text in the last line is horizontally aligned with the start edge.
46
47**Widget capability**: This API can be used in ArkTS widgets since API version 9.
48
49**Atomic service API**: This API can be used in atomic services since API version 11.
50
51**System capability**: SystemCapability.ArkUI.ArkUI.Full
52
53**Parameters**
54
55| Name| Type                                       | Mandatory| Description                                                      |
56| ------ | ------------------------------------------- | ---- | ---------------------------------------------------------- |
57| value  | [TextAlign](ts-appendix-enums.md#textalign) | Yes  | Horizontal alignment of the text.<br>Default value: **TextAlign.Start**|
58
59### textOverflow
60
61textOverflow(value: { overflow: TextOverflow })
62
63Sets the display mode when the text is too long.
64
65Text is clipped at the transition between words. To clip text in the middle of a word, add **\u200B** between characters. Since API version 11, preferably set the **wordBreak** attribute to **WordBreak.BREAK_ALL** to achieve the same purpose. For details, see [Example](#example-4).
66
67If **overflow** is set to **TextOverflow.None**, **TextOverflow.Clip**, or **TextOverflow.Ellipsis**, this attribute must be used with **maxLines** for the settings to take effect. **TextOverflow.None** produces the same effect as **TextOverflow.Clip**.
68
69If **overflow** is set to **TextOverflow.MARQUEE**, the text scrolls in a line, and neither **maxLines** nor **copyOption** takes effect. The **textAlign** attribute takes effect only when the text is not scrollable. With **overflow** set to **TextOverflow.MARQUEE**, the **clip** attribute is set to **true** by default. **TextOverflow.MARQUEE** is not available for [CustomSpan](ts-universal-styled-string.md#customspan) of the styled string.
70
71Since API version 12, **TextOverflow.MARQUEE** is available for the **\<ImageSpan>** component, where the text and images are displayed in scrolling mode in a line.
72
73**Widget capability**: This API can be used in ArkTS widgets since API version 9.
74
75**Atomic service API**: This API can be used in atomic services since API version 11.
76
77**System capability**: SystemCapability.ArkUI.ArkUI.Full
78
79**Parameters**
80
81| Name| Type                                                        | Mandatory| Description                                                        |
82| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
83| value  | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | Yes  | Display mode when the text is too long.<br>Default value: **{overflow: TextOverflow.Clip}**|
84
85### maxLines
86
87maxLines(value: number)
88
89Sets the maximum number of lines in the text. By default, text is automatically folded. If this attribute is specified, the text will not exceed the specified number of lines. If there is extra text, you can use [textOverflow](#textoverflow) to specify how it is displayed.
90
91**Widget capability**: This API can be used in ArkTS widgets since API version 9.
92
93**Atomic service API**: This API can be used in atomic services since API version 11.
94
95**System capability**: SystemCapability.ArkUI.ArkUI.Full
96
97**Parameters**
98
99| Name| Type  | Mandatory| Description            |
100| ------ | ------ | ---- | ---------------- |
101| value  | number | Yes  | Maximum number of lines in the text.|
102
103### lineHeight
104
105lineHeight(value: number | string | Resource)
106
107Sets the text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value is of the number type, the unit fp is used.
108
109**Widget capability**: This API can be used in ArkTS widgets since API version 9.
110
111**Atomic service API**: This API can be used in atomic services since API version 11.
112
113**System capability**: SystemCapability.ArkUI.ArkUI.Full
114
115**Parameters**
116
117| Name| Type                                                        | Mandatory| Description            |
118| ------ | ------------------------------------------------------------ | ---- | ---------------- |
119| value  | number \| string \| [Resource](ts-types.md#resource) | Yes  | Text line height.|
120
121### decoration
122
123decoration(value: DecorationStyleInterface)
124
125Sets the color, type, and style of the text decorative line.
126
127**Widget capability**: This API can be used in ArkTS widgets since API version 9.
128
129**Atomic service API**: This API can be used in atomic services since API version 11.
130
131**System capability**: SystemCapability.ArkUI.ArkUI.Full
132
133**Parameters**
134
135| Name| Type                                                        | Mandatory| Description                                                        |
136| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
137| value  | [DecorationStyleInterface<sup>12+</sup>](ts-universal-styled-string.md#decorationstyleinterface) | Yes  | Style of the text decorative line.<br>Default value:<br>{<br> type: TextDecorationType.None,<br> color: Color.Black,<br> style: TextDecorationStyle.SOLID <br>}<br>**NOTE**<br>The **style** parameter cannot be used in widgets.|
138
139### baselineOffset
140
141baselineOffset(value: number | string)
142
143Sets the offset of the text baseline. If the value specified is a percentage, the default value is used.
144
145**Widget capability**: This API can be used in ArkTS widgets since API version 9.
146
147**Atomic service API**: This API can be used in atomic services since API version 11.
148
149**System capability**: SystemCapability.ArkUI.ArkUI.Full
150
151**Parameters**
152
153| Name| Type                      | Mandatory| Description                            |
154| ------ | -------------------------- | ---- | -------------------------------- |
155| value  | number \| string | Yes  | Offset of the text baseline.<br>Default value: **0**|
156
157### letterSpacing
158
159letterSpacing(value: number | string)
160
161Sets the letter spacing for a text style. If the value specified is a percentage or 0, the default value is used.
162
163If the value specified is a negative value, the text is compressed. A negative value too small may result in the text being compressed to 0 and no content being displayed.
164
165**Widget capability**: This API can be used in ArkTS widgets since API version 9.
166
167**Atomic service API**: This API can be used in atomic services since API version 11.
168
169**System capability**: SystemCapability.ArkUI.ArkUI.Full
170
171**Parameters**
172
173| Name| Type                      | Mandatory| Description          |
174| ------ | -------------------------- | ---- | -------------- |
175| value  | number \| string | Yes  | Letter spacing.|
176
177### minFontSize
178
179minFontSize(value: number | string | Resource)
180
181Sets the minimum font size.
182
183For the setting to take effect, this attribute must be used together with [maxFontSize](#maxfontsize) and [maxlines](#maxlines), or layout constraint settings. In addition, it does not take effect for child components or styled strings.
184
185When the adaptive font size is used, the **fontSize** settings do not take effect.
186
187If the value of **minFontSize** is less than or equal to 0, the adaptive font size does not take effect.
188
189**Widget capability**: This API can be used in ArkTS widgets since API version 9.
190
191**Atomic service API**: This API can be used in atomic services since API version 11.
192
193**System capability**: SystemCapability.ArkUI.ArkUI.Full
194
195**Parameters**
196
197| Name| Type                                                        | Mandatory| Description              |
198| ------ | ------------------------------------------------------------ | ---- | ------------------ |
199| value  | number \| string \| [Resource](ts-types.md#resource) | Yes  | Minimum font size.|
200
201### maxFontSize
202
203maxFontSize(value: number | string | Resource)
204
205Sets the maximum font size.
206
207For the setting to take effect, this attribute must be used together with [minFontSize](#minfontsize) and [maxlines](#maxlines), or layout constraint settings. In addition, it does not take effect for child components or styled strings.
208
209When the adaptive font size is used, the **fontSize** settings do not take effect.
210
211**Widget capability**: This API can be used in ArkTS widgets since API version 9.
212
213**Atomic service API**: This API can be used in atomic services since API version 11.
214
215**System capability**: SystemCapability.ArkUI.ArkUI.Full
216
217**Parameters**
218
219| Name| Type                                                        | Mandatory| Description              |
220| ------ | ------------------------------------------------------------ | ---- | ------------------ |
221| value  | number \| string \| [Resource](ts-types.md#resource) | Yes  | Maximum font size.|
222
223### textCase
224
225textCase(value: TextCase)
226
227Sets the text case.
228
229**Widget capability**: This API can be used in ArkTS widgets since API version 9.
230
231**Atomic service API**: This API can be used in atomic services since API version 11.
232
233**System capability**: SystemCapability.ArkUI.ArkUI.Full
234
235**Parameters**
236
237| Name| Type                                     | Mandatory| Description                                     |
238| ------ | ----------------------------------------- | ---- | ----------------------------------------- |
239| value  | [TextCase](ts-appendix-enums.md#textcase) | Yes  | Text case.<br>Default value: **TextCase.Normal**|
240
241### fontColor
242
243fontColor(value: ResourceColor)
244
245Sets the font color.
246
247**Widget capability**: This API can be used in ArkTS widgets since API version 9.
248
249**Atomic service API**: This API can be used in atomic services since API version 11.
250
251**System capability**: SystemCapability.ArkUI.ArkUI.Full
252
253**Parameters**
254
255| Name| Type                                      | Mandatory| Description      |
256| ------ | ------------------------------------------ | ---- | ---------- |
257| value  | [ResourceColor](ts-types.md#resourcecolor) | Yes  | Font color.|
258
259### fontSize
260
261fontSize(value: number | string | Resource)
262
263Sets the text size.
264
265**Widget capability**: This API can be used in ArkTS widgets since API version 9.
266
267**Atomic service API**: This API can be used in atomic services since API version 11.
268
269**System capability**: SystemCapability.ArkUI.ArkUI.Full
270
271**Parameters**
272
273| Name| Type                                                        | Mandatory| Description                                                        |
274| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
275| value  | [Resource](ts-types.md#resource) \| number \| string | Yes  | Font size. If **fontSize** is of the number type, the unit fp is used. The default font size is 16 fp. This parameter cannot be set in percentage.|
276
277### fontStyle
278
279fontStyle(value: FontStyle)
280
281Sets the font style.
282
283**Widget capability**: This API can be used in ArkTS widgets since API version 9.
284
285**Atomic service API**: This API can be used in atomic services since API version 11.
286
287**System capability**: SystemCapability.ArkUI.ArkUI.Full
288
289**Parameters**
290
291| Name| Type                                       | Mandatory| Description                                   |
292| ------ | ------------------------------------------- | ---- | --------------------------------------- |
293| value  | [FontStyle](ts-appendix-enums.md#fontstyle) | Yes  | Font style.<br>Default value: **FontStyle.Normal**|
294
295### fontWeight
296
297fontWeight(value: number | FontWeight | string)
298
299Sets the font weight. If the value is too large, the text may be clipped depending on the font.
300
301**Widget capability**: This API can be used in ArkTS widgets since API version 9.
302
303**Atomic service API**: This API can be used in atomic services since API version 11.
304
305**System capability**: SystemCapability.ArkUI.ArkUI.Full
306
307**Parameters**
308
309| Name| Type                                                        | Mandatory| Description                                                        |
310| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
311| value  | [FontWeight](ts-appendix-enums.md#fontweight) \| number \| string | Yes  | Font weight. For the number type, the value range is [100, 900], at an interval of 100. The default value is **400**. A larger value indicates a heavier font weight. For the string type, only strings that represent a number, for example, **"400"**, and the following enumerated values of **FontWeight** are supported: **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**.<br>Default value: **FontWeight.Normal**|
312
313### fontFamily
314
315fontFamily(value: string | Resource)
316
317Sets the font family.
318
319**Widget capability**: This API can be used in ArkTS widgets since API version 9.
320
321**Atomic service API**: This API can be used in atomic services since API version 11.
322
323**System capability**: SystemCapability.ArkUI.ArkUI.Full
324
325**Parameters**
326
327| Name| Type                                                | Mandatory| Description                                                        |
328| ------ | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
329| value  | [Resource](ts-types.md#resource) \| string | Yes  | Font family. Default font: **'HarmonyOS Sans'**<br>The 'HarmonyOS Sans' font and [registered custom fonts](../js-apis-font.md) are supported for applications.<br>Only the 'HarmonyOS Sans' font is supported for widgets.|
330
331### copyOption<sup>9+</sup>
332
333copyOption(value: CopyOptions)
334
335Sets whether copy and paste is allowed. If this attribute is set to **CopyOptions.InApp** or **CopyOptions.LocalDevice**, a long press on the text will display a context menu that offers the copy and select-all options.
336
337Because widgets do not have the long press event, the context menu will not be displayed when users long press text.
338
339**Widget capability**: This API can be used in ArkTS widgets since API version 9.
340
341**Atomic service API**: This API can be used in atomic services since API version 11.
342
343**System capability**: SystemCapability.ArkUI.ArkUI.Full
344
345**Parameters**
346
347| Name| Type                                            | Mandatory| Description                                                      |
348| ------ | ------------------------------------------------ | ---- | ---------------------------------------------------------- |
349| value  | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Yes  | Whether copy and paste is allowed.<br>Default value: **CopyOptions.None**|
350
351### draggable<sup>9+</sup>
352
353draggable(value: boolean)
354
355Sets the drag effect of the selected text.
356
357This attribute cannot be used together with the [onDragStart](ts-universal-events-drag-drop.md) event.
358
359It must be used together with [CopyOptions](ts-appendix-enums.md#copyoptions9). When it is set to **true** and **copyOptions** is set to **CopyOptions.InApp** or **CopyOptions.LocalDevice**, the selected text can be dragged and copied to the text box.
360
361**Atomic service API**: This API can be used in atomic services since API version 11.
362
363**System capability**: SystemCapability.ArkUI.ArkUI.Full
364
365**Parameters**
366
367| Name| Type   | Mandatory| Description                                |
368| ------ | ------- | ---- | ------------------------------------ |
369| value  | boolean | Yes  | Drag effect of the selected text.<br>Default value: **false**|
370
371### font<sup>10+</sup>
372
373font(value: Font)
374
375Sets the text style, covering the font size, font width, font family, and font style.
376
377**Atomic service API**: This API can be used in atomic services since API version 11.
378
379**System capability**: SystemCapability.ArkUI.ArkUI.Full
380
381**Parameters**
382
383| Name| Type   | Mandatory| Description      |
384| ------ | ------- | ---- | ---------- |
385| value  | [Font](ts-types.md#font) | Yes  | Text style.|
386
387### textShadow<sup>10+</sup>
388
389textShadow(value: ShadowOptions | Array&lt;ShadowOptions&gt;)
390
391Sets the text shadow.
392
393This API does not work with the **fill** attribute or coloring strategy.
394
395Since API version 11, this API supports input parameters in an array to implement multiple text shadows.
396
397**Widget capability**: This API can be used in ArkTS widgets since API version 10.
398
399**Atomic service API**: This API can be used in atomic services since API version 11.
400
401**System capability**: SystemCapability.ArkUI.ArkUI.Full
402
403**Parameters**
404
405| Name| Type                                                        | Mandatory| Description          |
406| ------ | ------------------------------------------------------------ | ---- | -------------- |
407| value  | [ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions) \|  Array&lt;[ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions)&gt;<sup>11+</sup> | Yes  | Text shadow.|
408
409### heightAdaptivePolicy<sup>10+</sup>
410
411heightAdaptivePolicy(value: TextHeightAdaptivePolicy)
412
413Sets how the adaptive height is determined for the text.
414
415When this attribute is set to **TextHeightAdaptivePolicy.MAX_LINES_FIRST**, the [maxlines](#maxlines) attribute takes precedence for adjusting the text height. If the **maxLines** setting results in a layout beyond the layout constraints, the text will shrink to a font size between [minFontSize](#minfontsize) and [maxFontSize](#maxfontsize) to allow for more content to be shown.
416
417If this attribute is set to **TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST**, the **minFontSize** attribute takes precedence for adjusting the text height. If the text can fit in one line with the **minFontSize** setting, the text will enlarge to the largest possible font size between **minFontSize** and **maxFontSize**.
418
419If this attribute is set to **TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST**, the layout constraints take precedence for adjusting the text height. If the resultant layout is beyond the layout constraints, the text will shrink to a font size between **minFontSize** and **maxFontSize** to respect the layout constraints. If the text still extends beyond the layout constraints after shrinking to **minFontSize**, the lines that exceed the constraints are deleted.
420
421**Atomic service API**: This API can be used in atomic services since API version 11.
422
423**System capability**: SystemCapability.ArkUI.ArkUI.Full
424
425**Parameters**
426
427| Name| Type                                                        | Mandatory| Description                                                        |
428| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
429| value  | [TextHeightAdaptivePolicy](ts-appendix-enums.md#textheightadaptivepolicy10) | Yes  | How the adaptive height is determined for the text.<br>Default value: **TextHeightAdaptivePolicy.MAX_LINES_FIRST**|
430
431### textIndent<sup>10+</sup>
432
433textIndent(value: Length)
434
435Sets the indent of the first line text.
436
437**Atomic service API**: This API can be used in atomic services since API version 11.
438
439**System capability**: SystemCapability.ArkUI.ArkUI.Full
440
441**Parameters**
442
443| Name| Type                        | Mandatory| Description                        |
444| ------ | ---------------------------- | ---- | ---------------------------- |
445| value  | [Length](ts-types.md#length) | Yes  | Indent of the first line text.<br>Default value: **0**|
446
447### wordBreak<sup>11+</sup>
448
449wordBreak(value: WordBreak)
450
451Sets the word break rule. When used with **{overflow: TextOverflow.Ellipsis}** and **maxLines**, **WordBreak.BREAK_ALL** can insert line breaks between letters when overflow occurs and display excess content with an ellipsis (...).
452
453**Atomic service API**: This API can be used in atomic services since API version 11.
454
455**System capability**: SystemCapability.ArkUI.ArkUI.Full
456
457**Parameters**
458
459| Name| Type                                         | Mandatory| Description                                         |
460| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
461| value  | [WordBreak](ts-appendix-enums.md#wordbreak11) | Yes  | Word break rule.<br>Default value: **WordBreak.BREAK_WORD**|
462
463### selection<sup>11+</sup>
464
465selection(selectionStart: number, selectionEnd: number)
466
467Sets text selection. The selected text is highlighted, and a selection handle is displayed together with a menu of available actions.
468
469When **copyOption** is set to **CopyOptions.None**, the **selection** attribute is not effective.
470
471When **overflow** is set to **TextOverflow.MARQUEE**, the **selection** attribute is not effective.
472
473If the value of **selectionStart** is greater than or equal to that of **selectionEnd**, no text will be selected. The value range is [0, textSize], where **textSize** indicates the maximum number of characters in the text content. If the value is less than 0, the value **0** will be used. If the value is greater than **textSize**, **textSize** will be used.
474
475If the value of **selectionStart** or **selectionEnd** falls within the invisible area, no text will be selected. If clipping is disabled, the text selection outside of the parent component takes effect.
476
477**Atomic service API**: This API can be used in atomic services since API version 11.
478
479**System capability**: SystemCapability.ArkUI.ArkUI.Full
480
481**Parameters**
482
483| Name        | Type  | Mandatory| Description                                |
484| -------------- | ------ | ---- | ------------------------------------ |
485| selectionStart | number | Yes  | Start position of the selected text.<br>Default value: **-1**|
486| selectionEnd   | number | Yes  | End position of the selected text.<br>Default value: **-1**|
487
488### ellipsisMode<sup>11+</sup>
489
490ellipsisMode(value: EllipsisMode)
491
492Sets the ellipsis position. For the settings to work, **overflow** must be set to **TextOverflow.Ellipsis** and **maxLines** must be specified. Setting **ellipsisMode** alone does not take effect.
493
494**EllipsisMode.START** and **EllipsisMode.CENTER** take effect only when text overflows in a single line.
495
496**Atomic service API**: This API can be used in atomic services since API version 12.
497
498**System capability**: SystemCapability.ArkUI.ArkUI.Full
499
500**Parameters**
501
502| Name| Type                                               | Mandatory| Description                                     |
503| ------ | --------------------------------------------------- | ---- | ----------------------------------------- |
504| value  | [EllipsisMode](ts-appendix-enums.md#ellipsismode11) | Yes  | Ellipsis position.<br>Default value: **EllipsisMode.END**|
505
506### enableDataDetector<sup>11+</sup>
507
508enableDataDetector(enable: boolean)
509
510Enables recognition for special entities within the text.
511
512This API only works on devices that provide text recognition.
513
514When **enableDataDetector** is set to **true**, and the **dataDetectorConfig** attribute is not set, all types of entities are recognized by default, and the **color** and **decoration** of the recognized entities will be changed to the following styles:
515
516```ts
517color: '#ff007dff'
518decoration:{
519  type: TextDecorationType.Underline,
520  color: '#ff007dff',
521  style: TextDecorationStyle.SOLID
522}
523```
524
525Touching and right-clicking an entity with the mouse will pop up the corresponding entity operation menu based on the type of entity, while left-clicking an entity with the mouse will directly respond to the first option of the menu.
526
527This API does not work when **overflow** is set to **TextOverflow.MARQUEE**.
528
529When **copyOption** is set to **CopyOptions.None**, the menu displayed after an entity is clicked does not provide the text selection or copy functionality. When **copyOption** is not set to **CopyOptions.None**, and **textSelectable** is set to **TextSelectableMode.UNSELECTABLE**, the entity still has the copy functionality but does not have the text selection feature.
530
531**Atomic service API**: This API can be used in atomic services since API version 12.
532
533**System capability**: SystemCapability.ArkUI.ArkUI.Full
534
535**Parameters**
536
537| Name| Type   | Mandatory| Description                             |
538| ------ | ------- | ---- | --------------------------------- |
539| enable  | boolean | Yes  | Whether to enable text recognition.<br>Default value: **false**|
540
541### dataDetectorConfig<sup>11+</sup>
542
543dataDetectorConfig(config: TextDataDetectorConfig)
544
545Configures text recognition settings.
546
547This API must be used together with [enableDataDetector](#enabledatadetector11). It takes effect only when **enableDataDetector** is set to **true**.
548
549When entities A and B overlap, the following rules are followed:
550
5511. If A ⊂ B, retain B. Otherwise, retain A.
552
5532. When A ⊄ B and B ⊄ A: If A.start < B.start, retain A; otherwise, retain B.
554
555**Atomic service API**: This API can be used in atomic services since API version 12.
556
557**System capability**: SystemCapability.ArkUI.ArkUI.Full
558
559**Parameters**
560
561| Name| Type                                                       | Mandatory| Description                                                        |
562| ------ | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
563| config | [TextDataDetectorConfig](ts-text-common.md#textdatadetectorconfig11) | Yes  | Text recognition configuration.|
564
565### bindSelectionMenu<sup>11+</sup>
566
567bindSelectionMenu(spanType: TextSpanType, content: CustomBuilder, responseType: TextResponseType,
568    options?: SelectionMenuOptions)
569
570Sets the custom context menu on text selection.
571
572The duration required for a long-press gesture is 600 ms for **bindSelectionMenu** and 800 ms for **bindContextMenu**. When both **bindSelectionMenu** and **bindContextMenu** are set and both are configured to be triggered by a long-press gesture, **bindSelectionMenu** is triggered first.
573
574If the custom menu is too long, embed a [\<Scroll>](./ts-container-scroll.md) component to prevent the keyboard from being blocked.
575
576**Atomic service API**: This API can be used in atomic services since API version 12.
577
578**System capability**: SystemCapability.ArkUI.ArkUI.Full
579
580**Parameters**
581
582| Name      | Type                                                        | Mandatory| Description                                                        |
583| ------------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
584| spanType     | [TextSpanType](#textspantype11)          | Yes  | Span type of the menu.<br>Default value: **TextSpanType.TEXT**              |
585| content      | [CustomBuilder](ts-types.md#custombuilder8)                  | Yes  | Content of the menu.                                            |
586| responseType | [TextResponseType](#textresponsetype11)  | Yes  | Response type of the menu.<br>Default value: **TextResponseType.LONG_PRESS**|
587| options      | [SelectionMenuOptions](ts-appendix-enums.md#selectionmenuoptions11) | No  | Options of the menu.                                            |
588
589### fontFeature<sup>12+</sup>
590
591fontFeature(value: string)
592
593Sets the font feature, for example, monospaced digits.
594
595Format: normal \| \<feature-tag-value\>
596
597Format of **\<feature-tag-value\>**: \<string\> \[ \<integer\> \| on \| off ]
598
599There can be multiple **\<feature-tag-value\>** values, which are separated by commas (,).
600
601For example, the input format for monospaced clock fonts is "ss01" on.
602
603**Atomic service API**: This API can be used in atomic services since API version 12.
604
605**System capability**: SystemCapability.ArkUI.ArkUI.Full
606
607**Parameters**
608
609| Name| Type  | Mandatory| Description          |
610| ------ | ------ | ---- | -------------- |
611| value  | string | Yes  | Font feature.|
612
613Font feature list<br>
614![alt text](figures/arkts-fontfeature.png)
615
616Font features are advanced typographic features, such as ligatures and monospace, for OpenType fonts. They are typically used in custom fonts and require the support of the font itself.
617For more information about the font features, see [Low-level font feature settings control: the font-feature-settings property](https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop) and [The Complete CSS Demo for OpenType Features](https://sparanoid.com/lab/opentype-features/).
618
619>  **NOTE**<br/>
620>
621>  The **Text** component cannot contain both text and the child component **\<Span>** or **\<ImageSpan>**. If both of them exist, only the content in **\<Span>** or **\<ImageSpan>** is displayed.
622>
623>  The typesetting engine rounds down the value of [width](ts-universal-attributes-size.md#width) to ensure that the value is an integer. If the typesetting engine rounds up the value instead, the right side of the text may be clipped.
624>
625>  When multiple **Text** components are placed in the [\<Row>](ts-container-row.md) container with no specific layout or space allocation settings configured, the components are laid out based on the maximum size of the container. To make sure the sum of the components' main axis sizes does not exceed the main axis size of the container, you can set [layoutWeight](ts-universal-attributes-size.md#layoutweight) or use the [flex layout](ts-universal-attributes-flex-layout.md).
626
627### lineSpacing<sup>12+</sup>
628
629lineSpacing(value: LengthMetrics)
630
631Sets the line spacing of the text. If the value specified is less than or equal to 0, the default value **0** is used.
632
633**Atomic service API**: This API can be used in atomic services since API version 12.
634
635**System capability**: SystemCapability.ArkUI.ArkUI.Full
636
637**Parameters**
638
639| Name| Type                                                        | Mandatory| Description            |
640| ------ | ------------------------------------------------------------ | ---- | ---------------- |
641| value  | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes  | Line spacing. Default value: **0**|
642
643### privacySensitive<sup>12+</sup>
644
645privacySensitive(supported: boolean)
646
647Sets whether to enable privacy mode on widgets.
648
649**Widget capability**: This API can be used in ArkTS widgets since API version 12.
650
651**Atomic service API**: This API can be used in atomic services since API version 12.
652
653**System capability**: SystemCapability.ArkUI.ArkUI.Full
654
655**Parameters**
656
657| Name   | Type   | Mandatory| Description                                                        |
658| --------- | ------- | ---- | ------------------------------------------------------------ |
659| supported | boolean | Yes  | Whether to enable privacy mode on widgets.<br>The value **true** means to enable privacy mode, in which case text is obscured as hyphens (-).<br>Default value: **false**<br>**NOTE**<br>If this parameter is set to **null**, privacy mode is disabled.<br>Enabling privacy mode requires [widget framework support](./ts-universal-attributes-obscured.md).|
660
661### lineBreakStrategy<sup>12+</sup>
662
663lineBreakStrategy(strategy: LineBreakStrategy)
664
665Sets the line break rule. This attribute takes effect when **wordBreak** is not set to **breakAll**. Hyphens are not supported.
666
667**Atomic service API**: This API can be used in atomic services since API version 12.
668
669**System capability**: SystemCapability.ArkUI.ArkUI.Full
670
671**Parameters**
672
673| Name  | Type                                                        | Mandatory| Description                                                   |
674| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------- |
675| strategy | [LineBreakStrategy](ts-appendix-enums.md#linebreakstrategy12) | Yes  | Line break rule.<br>Default value: **LineBreakStrategy.GREEDY**|
676
677### textSelectable<sup>12+</sup>
678
679textSelectable(mode: TextSelectableMode)
680
681Sets whether the text is selectable and focusable.
682
683**Atomic service API**: This API can be used in atomic services since API version 12.
684
685**System capability**: SystemCapability.ArkUI.ArkUI.Full
686
687**Parameters**
688
689| Name| Type                                         | Mandatory| Description                                         |
690| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
691| mode  | [TextSelectableMode](ts-appendix-enums.md#textselectablemode12) | Yes  | Whether the text is selectable and focusable.<br>Default value: **TextSelectableMode.SELECTABLE_UNFOCUSABLE**|
692
693### editMenuOptions<sup>12+</sup>
694
695editMenuOptions(editMenu: EditMenuOptions)
696
697Sets the extended options of the custom context menu on selection, including the text content, icon, and callback.
698
699**Atomic service API**: This API can be used in atomic services since API version 12.
700
701**System capability**: SystemCapability.ArkUI.ArkUI.Full
702
703**Parameters**
704
705| Name| Type                                         | Mandatory| Description                                         |
706| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
707| editMenu  | [EditMenuOptions](ts-text-common.md#editmenuoptions) | Yes  | Extended options of the custom context menu on selection.|
708
709### minFontScale<sup>12+</sup>
710
711minFontScale(scale: number | Resource)
712
713Sets the minimum font scale factor for text.
714
715**Atomic service API**: This API can be used in atomic services since API version 12.
716
717**System capability**: SystemCapability.ArkUI.ArkUI.Full
718
719**Parameters**
720
721| Name| Type                                         | Mandatory| Description                                         |
722| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
723| scale  | number \| [Resource](ts-types.md#resource) | Yes  | Minimum font scale factor for text.<br>Value range: (0,1]<br>**NOTE**<br>A value less than 0 is handed as **0**. A value greater than 1 is handed as **1**. Abnormal values are ineffective by default.|
724
725### maxFontScale<sup>12+</sup>
726
727maxFontScale(scale: number | Resource)
728
729Sets the maximum font scale factor for text.
730
731**Atomic service API**: This API can be used in atomic services since API version 12.
732
733**System capability**: SystemCapability.ArkUI.ArkUI.Full
734
735**Parameters**
736
737| Name| Type                                         | Mandatory| Description                                         |
738| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
739| scale  | number \| [Resource](ts-types.md#resource) | Yes  | Maximum font scale factor for text.<br>Value range: [1, +∞)<br>**NOTE**<br>A value less than 1 is handed as **1**. Abnormal values are ineffective by default.|
740
741### halfLeading<sup>12+</sup>
742
743halfLeading(halfLeading: boolean)
744
745Sets whether half leading is enabled.
746
747The **halfLeading** settings configured within the component take precedence over those in **module.json5**.
748
749**Atomic service API**: This API can be used in atomic services since API version 12.
750
751**System capability**: SystemCapability.ArkUI.ArkUI.Full
752
753**Parameters**
754
755| Name| Type                                         | Mandatory| Description                                         |
756| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
757| halfLeading | boolean | Yes | Whether half leading is enabled.<br>Half leading is the leading split in half and applied equally to the top and bottom edges. The value **true** means that half leading is enabled, and **false** means the opposite.<br>Default value: **false**|
758
759### font<sup>12+</sup>
760
761font(fontValue: Font, options?: FontSettingOptions)
762
763Sets the font style, with support for font settings.
764
765It is only effective for the **Text** component, not for its child components.
766
767**Widget capability**: This API can be used in ArkTS widgets since API version 12.
768
769**Atomic service API**: This API can be used in atomic services since API version 12.
770
771**System capability**: SystemCapability.ArkUI.ArkUI.Full
772
773**Parameters**
774
775| Name| Type                                         | Mandatory| Description                                         |
776| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
777| fontValue | [Font](ts-types.md#font) | Yes | Sets the text style,|
778| options | [FontSettingOptions](ts-text-common.md#fontsettingoptions12) | No | Font settings.|
779
780### fontWeight<sup>12+</sup>
781
782fontWeight(weight: number | FontWeight | string, options?: FontSettingOptions)
783
784Sets the text font weight, with support for font settings.
785
786It is only effective for the **Text** component, not for its child components.
787
788**Widget capability**: This API can be used in ArkTS widgets since API version 12.
789
790**Atomic service API**: This API can be used in atomic services since API version 12.
791
792**System capability**: SystemCapability.ArkUI.ArkUI.Full
793
794**Parameters**
795
796| Name| Type                                         | Mandatory| Description                                         |
797| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
798| weight | [FontWeight](ts-appendix-enums.md#fontweight) \| number \| string | Yes | Font weight.|
799| options | [FontSettingOptions](ts-text-common.md#fontsettingoptions12) | No | Font settings.|
800
801## TextSpanType<sup>11+</sup>
802
803Provides the [span](ts-basic-components-span.md) type information.
804
805**Atomic service API**: This API can be used in atomic services since API version 12.
806
807**System capability**: SystemCapability.ArkUI.ArkUI.Full
808
809| Name| Description|
810| -------- | -------- |
811| TEXT | Text span.|
812| IMAGE | Image span.|
813| MIXED | Mixed span, which contains both text and imagery.|
814
815## TextResponseType<sup>11+</sup>
816
817**Atomic service API**: This API can be used in atomic services since API version 12.
818
819**System capability**: SystemCapability.ArkUI.ArkUI.Full
820
821| Name        | Description           |
822| ---------- | ------------- |
823| RIGHT_CLICK | The menu is displayed when the component is right-clicked.|
824| LONG_PRESS  | The menu is displayed when the component is long-pressed.  |
825| SELECT | The menu is displayed when the component is selected.|
826
827## Events
828
829In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
830
831### onCopy<sup>11+</sup>
832
833onCopy(callback:(value: string) =&gt; void)
834
835Called when data is copied to the pasteboard, which is displayed when the text box is long pressed. Currently, only text can be copied.
836
837**Atomic service API**: This API can be used in atomic services since API version 11.
838
839**System capability**: SystemCapability.ArkUI.ArkUI.Full
840
841**Parameters**
842
843| Name| Type  | Mandatory| Description            |
844| ------ | ------ | ---- | ---------------- |
845| value  | string | Yes  | Text that is copied.|
846
847### onTextSelectionChange<sup>11+</sup>
848
849onTextSelectionChange(callback: (selectionStart: number, selectionEnd: number) => void)
850
851Called when the text selection position changes.
852
853**Atomic service API**: This API can be used in atomic services since API version 12.
854
855**System capability**: SystemCapability.ArkUI.ArkUI.Full
856
857**Parameters**
858
859| Name        | Type  | Mandatory| Description                |
860| -------------- | ------ | ---- | -------------------- |
861| selectionStart | number | Yes  | Start position of the selected text.|
862| selectionEnd   | number | Yes  | End position of the selected text.|
863
864## TextOptions<sup>11+</sup>
865
866Describes the initialization options of the **Text** component.
867
868**Atomic service API**: This API can be used in atomic services since API version 12.
869
870**System capability**: SystemCapability.ArkUI.ArkUI.Full
871
872| Name| Type| Mandatory| Description|
873| -------- | -------- | -------- | -------- |
874| controller | [TextController](#textcontroller11)  | Yes| Text controller.|
875
876## TextController<sup>11+</sup>
877
878Defines the controller of the **Text** component.
879
880**Atomic service API**: This API can be used in atomic services since API version 12.
881
882**System capability**: SystemCapability.ArkUI.ArkUI.Full
883
884### Objects to Import
885
886```
887controller: TextController = new TextController()
888```
889
890### closeSelectionMenu
891
892closeSelectionMenu(): void
893
894Closes the custom or default context menu on selection.
895
896**Atomic service API**: This API can be used in atomic services since API version 12.
897
898**System capability**: SystemCapability.ArkUI.ArkUI.Full
899
900### setStyledString<sup>12+</sup>
901
902setStyledString(value: StyledString): void
903
904Binds to or updates the specified styled string.
905
906**Atomic service API**: This API can be used in atomic services since API version 12.
907
908**System capability**: SystemCapability.ArkUI.ArkUI.Full
909
910**Parameters**
911
912| Name  | Type  | Mandatory  | Description               |
913| ----- | ------ | ---- | ------------------- |
914| value | [StyledString](ts-universal-styled-string.md#styledstring) | Yes   | Styled string.<br>**NOTE**<br>The child class [MutableStyledString](ts-universal-styled-string.md#mutablestyledstring) of **StyledString** can also serve as the argument.|
915
916### getLayoutManager<sup>12+</sup>
917
918getLayoutManager(): LayoutManager
919
920Obtains the **LayoutManager** object.
921
922**Atomic service API**: This API can be used in atomic services since API version 12.
923
924**System capability**: SystemCapability.ArkUI.ArkUI.Full
925
926**Return value**
927
928| Type                                      | Description     |
929| ---------------------------------------- | ------- |
930| [LayoutManager](ts-text-common.md#LayoutManager) | **LayoutManager** object.|
931
932## Example
933
934### Example 1
935
936This example shows how to set the **textAlign**, **maxLines**, **textOverflow**, and **lineHeight** attributes.
937
938```ts
939// xxx.ets
940@Extend(Text)
941function style(TextAlign: TextAlign) {
942  .textAlign(TextAlign)
943  .fontSize(12)
944  .border({ width: 1 })
945  .padding(10)
946  .width('100%')
947}
948
949@Entry
950@Component
951struct TextExample1 {
952  build() {
953    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
954      // Set the horizontal alignment for the text.
955      // Single-line text
956      Text('textAlign').fontSize(9).fontColor(0xCCCCCC)
957      Text('TextAlign set to Center.')
958        .style(TextAlign.Center)
959      Text('TextAlign set to Start.')
960        .style(TextAlign.Start)
961      Text('TextAlign set to End.')
962        .style(TextAlign.End)
963
964      // Multi-line text
965      Text('This is the text content with textAlign set to Center.')
966        .style(TextAlign.Center)
967      Text('This is the text content with textAlign set to Start.')
968        .style(TextAlign.Start)
969      Text('This is the text content with textAlign set to End.')
970        .style(TextAlign.End)
971
972
973      // Set the display mode when the text is too long.
974      Text('TextOverflow+maxLines').fontSize(9).fontColor(0xCCCCCC)
975      // Clip the text when the value of maxLines is exceeded.
976      Text('This is the setting of textOverflow to Clip text content This is the setting of textOverflow to None text content. This is the setting of textOverflow to Clip text content This is the setting of textOverflow to None text content.')
977        .textOverflow({ overflow: TextOverflow.Clip })
978        .maxLines(1)
979        .style(TextAlign.Start)
980
981      // Show an ellipsis (...) when the value of maxLines is exceeded.
982      Text('This is set textOverflow to Ellipsis text content This is set textOverflow to Ellipsis text content.')
983        .textOverflow({ overflow: TextOverflow.Ellipsis })
984        .maxLines(1)
985        .style(TextAlign.Start)
986
987      Text('lineHeight').fontSize(9).fontColor(0xCCCCCC)
988      Text('This is the text with the line height set. This is the text with the line height set.')
989        .style(TextAlign.Start)
990      Text('This is the text with the line height set. This is the text with the line height set.')
991        .style(TextAlign.Start)
992        .lineHeight(20)
993    }.height(600).width(340).padding({ left: 35, right: 35, top: 35 })
994  }
995}
996```
997![textExp1](figures/textExp1.png)
998
999### Example 2
1000
1001This example shows how to set the **decoration**, **baselineOffset**, **letterSpacing**, and **textCase** attributes.
1002
1003```ts
1004@Extend(Text)
1005function style() {
1006  .fontSize(12)
1007  .border({ width: 1 })
1008  .padding(10)
1009  .width('100%')
1010}
1011
1012@Entry
1013@Component
1014struct TextExample2 {
1015  build() {
1016    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
1017      Text('decoration').fontSize(9).fontColor(0xCCCCCC)
1018      Text('This is the text content with the decoration set to LineThrough and the color set to Red.')
1019        .decoration({
1020          type: TextDecorationType.LineThrough,
1021          color: Color.Red
1022        })
1023        .style()
1024
1025      Text('This is the text content with the decoration set to Overline and the color set to Red.')
1026        .decoration({
1027          type: TextDecorationType.Overline,
1028          color: Color.Red,
1029          style: TextDecorationStyle.DOTTED
1030        })
1031        .style()
1032
1033      Text('This is the text content with the decoration set to Underline and the color set to Red.')
1034        .decoration({
1035          type: TextDecorationType.Underline,
1036          color: Color.Red,
1037          style: TextDecorationStyle.WAVY
1038        })
1039        .style()
1040
1041      // Set the offset of the text baseline.
1042      Text('baselineOffset').fontSize(9).fontColor(0xCCCCCC)
1043      Text('This is the text content with baselineOffset 0.')
1044        .baselineOffset(0)
1045        .style()
1046      Text('This is the text content with baselineOffset 30.')
1047        .baselineOffset(30)
1048        .style()
1049      Text('This is the text content with baselineOffset -20.')
1050        .baselineOffset(-20)
1051        .style()
1052
1053      // Set the letter spacing.
1054      Text('letterSpacing').fontSize(9).fontColor(0xCCCCCC)
1055      Text('This is the text content with letterSpacing 0.')
1056        .letterSpacing(0)
1057        .style()
1058      Text('This is the text content with letterSpacing 3.')
1059        .letterSpacing(3)
1060        .style()
1061      Text('This is the text content with letterSpacing -1.')
1062        .letterSpacing(-1)
1063        .style()
1064
1065      Text('textCase').fontSize(9).fontColor(0xCCCCCC)
1066      Text('This is the text content with textCase set to Normal.')
1067        .textCase(TextCase.Normal)
1068        .style()
1069      // Display the text in lowercase.
1070      Text('This is the text content with textCase set to LowerCase.')
1071        .textCase(TextCase.LowerCase)
1072        .style()
1073      // Display the text in uppercase.
1074      Text('This is the text content with textCase set to UpperCase.')
1075        .textCase(TextCase.UpperCase)
1076        .style()
1077
1078    }.height(700).width(350).padding({ left: 35, right: 35, top: 35 })
1079  }
1080}
1081```
1082![textExp1](figures/textExp2.png)
1083
1084### Example 3
1085
1086This example shows how to use **textShadow**, **heightAdaptivePolicy**, and **TextOverflow.MARQUEE**.
1087
1088```ts
1089@Extend(Text)
1090function style(HeightAdaptivePolicy: TextHeightAdaptivePolicy) {
1091  .width('80%')
1092  .height(90)
1093  .borderWidth(1)
1094  .minFontSize(10)
1095  .maxFontSize(30)
1096  .maxLines(2)
1097  .textOverflow({ overflow: TextOverflow.Ellipsis })
1098  .heightAdaptivePolicy(HeightAdaptivePolicy)
1099}
1100
1101@Entry
1102@Component
1103struct TextExample3 {
1104  build() {
1105    Column() {
1106      Text('textShadow').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%')
1107      // Set the text shadow.
1108      Text('textShadow')
1109        .width('80%')
1110        .height(55)
1111        .fontSize(40)
1112        .lineHeight(55)
1113        .textAlign(TextAlign.Center)
1114        .textShadow({
1115          radius: 10,
1116          color: Color.Black,
1117          offsetX: 0,
1118          offsetY: 0
1119        })
1120        .borderWidth(1)
1121      Divider()
1122      // Set how the adaptive height is determined for the text.
1123      Text('heightAdaptivePolicy').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%')
1124      Text('This is the text with the height adaptive policy set')
1125        .style(TextHeightAdaptivePolicy.MAX_LINES_FIRST)
1126      Text('This is the text with the height adaptive policy set')
1127        .style(TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST)
1128      Text('This is the text with the height adaptive policy set')
1129        .style(TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST)
1130      Divider()
1131      Text('marquee').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%')
1132      // Set the text to continuously scroll when text overflow occurs.
1133      Text('This is the text with the text overflow set marquee')
1134        .width(300)
1135        .borderWidth(1)
1136        .textOverflow({ overflow: TextOverflow.MARQUEE })
1137    }
1138  }
1139}
1140```
1141
1142![](figures/text_3.gif)
1143
1144### Example 4
1145This example shows how to use **ellipsisMode** and **wordBreak**.
1146
1147```ts
1148// xxx.ets
1149@Entry
1150@Component
1151struct TextExample4 {
1152  @State text: string =
1153    'The text component is used to display a piece of textual information.Support universal attributes and universal text attributes.'
1154  @State ellipsisModeIndex: number = 0;
1155  @State ellipsisMode: EllipsisMode[] = [EllipsisMode.START, EllipsisMode.CENTER, EllipsisMode.END]
1156  @State ellipsisModeStr: string[] = ['START', 'CENTER', 'END']
1157  @State wordBreakIndex: number = 0;
1158  @State wordBreak: WordBreak[] = [WordBreak.NORMAL, WordBreak.BREAK_ALL, WordBreak.BREAK_WORD]
1159  @State wordBreakStr: string[] = ['NORMAL', 'BREAK_ALL', 'BREAK_WORD']
1160  @State textClip: boolean = false
1161
1162  build() {
1163    Column({ space: 10 }) {
1164      Text(this.text)
1165        .fontSize(16)
1166        .border({ width: 1 })
1167        .lineHeight(20)
1168        .maxLines(1)
1169        .textOverflow({ overflow: TextOverflow.Ellipsis })
1170        .ellipsisMode(this.ellipsisMode[this.ellipsisModeIndex])
1171        .width(300)
1172        .margin({ left: 20, top: 20 })
1173
1174      Row() {
1175        Button('Change Ellipsis Position:' + this.ellipsisModeStr[this.ellipsisModeIndex]).onClick (() => {
1176          this.ellipsisModeIndex++
1177          if (this.ellipsisModeIndex > (this.ellipsisModeStr.length - 1)) {
1178            this.ellipsisModeIndex = 0
1179          }
1180        })
1181      }
1182
1183      Text('This is set wordBreak to WordBreak text Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu.')
1184        .fontSize(12)
1185        .border({ width: 1 })
1186        .wordBreak(WordBreak.NORMAL)
1187        .lineHeight(20)
1188        .maxLines(2)
1189        .clip(this.textClip)
1190        .width(260)
1191      Row() {
1192        Button('Change Clip Mode: ' + this.textClip).onClick(() => {
1193          this.textClip = !this.textClip
1194        })
1195      }
1196
1197      Text(this.text)
1198        .fontSize(12)
1199        .border({ width: 1 })
1200        .maxLines(2)
1201        .textOverflow({ overflow: TextOverflow.Ellipsis })
1202        .wordBreak(this.wordBreak[this.wordBreakIndex])
1203        .lineHeight(20)
1204        .width(260)
1205      Row() {
1206        Button('Change wordBreak Mode: ' + this.wordBreakStr[this.wordBreakIndex]).onClick(() => {
1207          this.wordBreakIndex++
1208          if (this.wordBreakIndex > (this.wordBreakStr.length - 1)) {
1209            this.wordBreakIndex = 0
1210          }
1211        })
1212      }
1213    }
1214  }
1215}
1216```
1217
1218![](figures/textExample4.gif)
1219
1220### Example 5
1221This example shows how to use **selection** and **onCopy**.
1222
1223```ts
1224@Entry
1225@Component
1226struct TextExample5 {
1227  @State onCopy: string = ''
1228  @State text: string = 'This is set selection to Selection text content This is set selection to Selection text content.'
1229  @State start: number = 0
1230  @State end: number = 20
1231
1232  build() {
1233    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.Start }) {
1234      Text(this.text)
1235        .fontSize(12)
1236        .border({ width: 1 })
1237        .lineHeight(20)
1238        .margin(30)
1239        .copyOption(CopyOptions.InApp)
1240        .selection(this.start, this.end)
1241        .onCopy((value: string) => {
1242          this.onCopy = value
1243        })
1244      Button('Set text selection')
1245        .margin({left:20})
1246        .onClick(() => {
1247          // Change the start point and end point of the text selection.
1248          this.start = 10
1249          this.end = 30
1250        })
1251      Text(this.onCopy).fontSize(12).margin(10).key('copy')
1252    }.height(600).width(335).padding({ left: 35, right: 35, top: 35 })
1253  }
1254}
1255```
1256![](figures/textExample5.png)
1257
1258### Example 6
1259This example shows how to use **enableDataDetector** and **dataDetectorConfig**.
1260
1261```ts
1262@Entry
1263@Component
1264struct TextExample6 {
1265  @State phoneNumber: string = '(86) (755) ********';
1266  @State url: string = 'www.********.com';
1267  @State email: string = '***@example.com';
1268  @State address: string = 'XX (province) XX (city) XX (county) XXXX';
1269  @State datetime: string = 'XX-XX-XX XXXX';
1270  @State enableDataDetector: boolean = true;
1271  @State types: TextDataDetectorType[] = [];
1272
1273  build() {
1274    Row() {
1275      Column() {
1276        Text(
1277          'Phone number:' + this.phoneNumber + '\n' +
1278          'URL:' + this.url + '\n' +
1279          'Email:' + this.email + '\n' +
1280          'Address:' + this.address + '\n' +
1281          'Time:' + this.datetime
1282        )
1283          .fontSize(16)
1284          .copyOption(CopyOptions.InApp)
1285          .enableDataDetector(this.enableDataDetector)
1286          .dataDetectorConfig({types : this.types, onDetectResultUpdate: (result: string)=>{}})
1287          .textAlign(TextAlign.Center)
1288          .borderWidth(1)
1289          .padding(10)
1290          .width('100%')
1291      }
1292      .width('100%')
1293    }
1294    .height('100%')
1295  }
1296}
1297```
1298
1299![](figures/text7.png)
1300
1301### Example 7
1302
1303This example shows how to use **bindSelectionMenu**, **onTextSelectionChange**, and **closeSelectionMenu**.
1304
1305```ts
1306@Entry
1307@Component
1308struct TextExample7 {
1309  controller: TextController = new TextController();
1310  options: TextOptions = { controller: this.controller };
1311
1312  build() {
1313    Column() {
1314      Column() {
1315        Text(undefined, this.options) {
1316          Span('Hello World')
1317          ImageSpan($r('app.media.icon'))
1318            .width('100px')
1319            .height('100px')
1320            .objectFit(ImageFit.Fill)
1321            .verticalAlign(ImageSpanAlignment.CENTER)
1322        }
1323        .copyOption(CopyOptions.InApp)
1324        .bindSelectionMenu(TextSpanType.IMAGE, this.LongPressImageCustomMenu, TextResponseType.LONG_PRESS, {
1325          onDisappear: () => {
1326            console.info(`Triggered when the custom context menu on selection is closed.`);
1327          },
1328          onAppear: () => {
1329            console.info(`Triggered when the custom context menu on selection is displayed`);
1330          }
1331        })
1332        .bindSelectionMenu(TextSpanType.TEXT, this.RightClickTextCustomMenu, TextResponseType.RIGHT_CLICK)
1333        .bindSelectionMenu(TextSpanType.MIXED, this.SelectMixCustomMenu, TextResponseType.SELECT)
1334        .onTextSelectionChange((selectionStart: number, selectionEnd: number) => {
1335          console.info(`Triggered when the text selection position changes, selectionStart: ${selectionStart}, selectionEnd: ${selectionEnd}`);
1336        })
1337        .borderWidth(1)
1338        .borderColor(Color.Red)
1339        .width(200)
1340        .height(100)
1341      }
1342      .width('100%')
1343      .backgroundColor(Color.White)
1344      .alignItems(HorizontalAlign.Start)
1345      .padding(25)
1346    }
1347    .height('100%')
1348  }
1349
1350  @Builder
1351  RightClickTextCustomMenu() {
1352    Column() {
1353      Menu() {
1354        MenuItemGroup() {
1355          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 1", labelInfo: "" })
1356            .onClick((event) => {
1357              this.controller.closeSelectionMenu();
1358            })
1359          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 2", labelInfo: "" })
1360          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 3", labelInfo: "" })
1361        }
1362      }
1363      .MenuStyles()
1364    }
1365  }
1366
1367  @Builder
1368  LongPressImageCustomMenu() {
1369    Column() {
1370      Menu() {
1371        MenuItemGroup() {
1372          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 1", labelInfo: "" })
1373            .onClick((event) => {
1374              this.controller.closeSelectionMenu();
1375            })
1376          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 2", labelInfo: "" })
1377          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 3", labelInfo: "" })
1378        }
1379      }
1380      .MenuStyles()
1381    }
1382  }
1383
1384  @Builder
1385  SelectMixCustomMenu() {
1386    Column() {
1387      Menu() {
1388        MenuItemGroup() {
1389          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 1", labelInfo: "" })
1390            .onClick((event) => {
1391              this.controller.closeSelectionMenu();
1392            })
1393          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 2", labelInfo: "" })
1394          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 3", labelInfo: "" })
1395        }
1396      }
1397      .MenuStyles()
1398    }
1399  }
1400}
1401
1402@Extend(Menu)
1403function MenuStyles() {
1404  .radius($r('sys.float.ohos_id_corner_radius_card'))
1405  .clip(true)
1406  .backgroundColor('#F0F0F0')
1407}
1408```
1409
1410![](figures/textBindSelectionMenu.gif)
1411
1412### Example 8
1413This example shows how to use **fontFeature**, **lineSpacing**, and **lineBreakStrategy**.
1414
1415```ts
1416import { LengthMetrics } from '@kit.ArkUI'
1417
1418@Extend(Text) function lineSpacingValue(LineSpacing: LengthMetrics|undefined) {
1419  .lineSpacing(LineSpacing)
1420  .fontSize(12)
1421  .border({ width: 1 })
1422}
1423@Entry
1424@Component
1425struct TextExample8 {
1426  @State message1: string = "They can be classified as built-in components–those directly provided by the ArkUI framework and custom components – those defined by developers" +
1427    "The built-in components include buttons radio buttonsprogress indicators and text You can set the rendering effectof thesecomponents in method chaining mode," +
1428    "page components are divided into independent UI units to implementindependent creation development and reuse of different units on pages making pages more engineering-oriented.";
1429  @State lineBreakStrategyIndex: number = 0;
1430  @State lineBreakStrategy: LineBreakStrategy[] = [LineBreakStrategy.GREEDY, LineBreakStrategy.HIGH_QUALITY, LineBreakStrategy.BALANCED]
1431  @State lineBreakStrategyStr: string[] = ['GREEDY', 'HIGH_QUALITY', 'BALANCED']
1432  build() {
1433    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
1434      Text('lineSpacing').fontSize(9).fontColor(0xCCCCCC)
1435      Text('This is a context with no lineSpacing set.')
1436        .lineSpacingValue(undefined)
1437      Text( 'This is a context with lineSpacing set to 20_px.')
1438        .lineSpacingValue(LengthMetrics.px(20))
1439      Text('This is the context with lineSpacing set to 20_vp.')
1440        .lineSpacingValue(LengthMetrics.vp(20))
1441      Text('This is the context with lineSpacing set to 20_fp.')
1442        .lineSpacingValue(LengthMetrics.fp(20))
1443      Text('This is the context with lineSpacing set to 20_lpx.')
1444        .lineSpacingValue(LengthMetrics.lpx(20))
1445      Text('This is the context with lineSpacing set to 100%.')
1446        .lineSpacingValue(LengthMetrics.percent(1))
1447      Text('fontFeature').fontSize(9).fontColor(0xCCCCCC)
1448      Text('This is ss01 on : 0123456789')
1449        .fontSize(20)
1450        .fontFeature("\"ss01\" on")
1451      Text('This is ss01 off: 0123456789')
1452        .fontSize(20)
1453        .fontFeature("\"ss01\" off")
1454      Text('lineBreakStrategy').fontSize(9).fontColor(0xCCCCCC)
1455      Text(this.message1)
1456        .fontSize(12)
1457        .border({ width: 1 })
1458        .padding(10)
1459        .width('100%')
1460        .lineBreakStrategy(this.lineBreakStrategy[this.lineBreakStrategyIndex])
1461      Row() {
1462        Button('Change lineBreakStrategy Value:' + this.lineBreakStrategyStr[this.lineBreakStrategyIndex]).onClick(() => {
1463          this.lineBreakStrategyIndex++
1464          if(this.lineBreakStrategyIndex > (this.lineBreakStrategyStr.length - 1)) {
1465            this.lineBreakStrategyIndex = 0
1466          }
1467        })
1468      }
1469    }.height(600).width(350).padding({ left: 35, right: 35, top: 35 })
1470  }
1471}
1472```
1473
1474![](figures/TextExample8.gif)
1475
1476### Example 9
1477This example shows how to use **getLayoutManager**.
1478
1479```ts
1480@Entry
1481@Component
1482struct TextExample9 {
1483  @State lineCount: string = ""
1484  @State glyphPositionAtCoordinate: string = ""
1485  @State lineMetrics: string = ""
1486  controller: TextController = new TextController()
1487  @State textStr: string =
1488    'Hello World!'
1489
1490  build() {
1491    Scroll() {
1492      Column() {
1493        Text('Use getLayoutManager to get layout information')
1494          .fontSize(9)
1495          .fontColor(0xCCCCCC)
1496          .width('90%')
1497          .padding(10)
1498        Text(this.textStr, { controller: this.controller })
1499          .fontSize(25)
1500          .borderWidth(1)
1501          .onAreaChange(() => {
1502            let layoutManager: LayoutManager = this.controller.getLayoutManager()
1503            this.lineCount = "LineCount: " + layoutManager.getLineCount()
1504          })
1505
1506        Text('LineCount').fontSize(9).fontColor(0xCCCCCC).width('90%').padding(10)
1507        Text(this.lineCount)
1508
1509        Text('GlyphPositionAtCoordinate').fontSize(9).fontColor(0xCCCCCC).width('90%').padding(10)
1510        Button("Relative Component Coordinates [150,50]")
1511          .onClick(() => {
1512            let layoutManager: LayoutManager = this.controller.getLayoutManager()
1513            let position: PositionWithAffinity = layoutManager.getGlyphPositionAtCoordinate(150, 50)
1514            this.glyphPositionAtCoordinate =
1515              "Relative component coordinates [150,50] glyphPositionAtCoordinate position: " + position.position + " affinity: " +
1516              position.affinity
1517          })
1518          .margin({ bottom: 20, top: 10 })
1519        Text(this.glyphPositionAtCoordinate)
1520
1521        Text('LineMetrics').fontSize(9).fontColor(0xCCCCCC).width('90%').padding(10)
1522        Button("Line Metrics")
1523          .onClick(() => {
1524            let layoutManager: LayoutManager = this.controller.getLayoutManager()
1525            let lineMetrics: LineMetrics = layoutManager.getLineMetrics(0)
1526            this.lineMetrics = "lineMetrics is " + JSON.stringify(lineMetrics) + '\n\n'
1527            let runMetrics = lineMetrics.runMetrics
1528            runMetrics.forEach((value, key) => {
1529              this.lineMetrics += "runMetrics key is " + key + " " + JSON.stringify(value) + "\n\n"
1530            });
1531          })
1532          .margin({ bottom: 20, top: 10 })
1533        Text(this.lineMetrics)
1534      }
1535      .margin({ top: 100, left: 8, right: 8 })
1536    }
1537  }
1538}
1539```
1540
1541![textLayoutManager](figures/textLayoutManager.gif)
1542
1543### Example 10
1544This example shows how to use **textSelectable**: With **TextSelectMode.SELECTABLE_FOCUSABLE** set, the text can be selected with the keyboard.
1545
1546```ts
1547@Entry
1548@Component
1549struct TextExample10 {
1550  @State message: string = 'TextTextTextTextTextTextTextText' + 'TextTextTextTextTextTextTextTextTextTextTextTextTextTextTextText';
1551  
1552  build() {
1553    Column() {
1554      Text(this.message)
1555        .width(300)
1556        .height(100)
1557        .maxLines(5)
1558        .fontColor(Color.Black)
1559        .copyOption(CopyOptions.InApp)
1560        .selection(3, 8)
1561        .textSelectable(TextSelectableMode.SELECTABLE_FOCUSABLE)
1562    }.width('100%').margin({ top: 100 })
1563  }
1564}
1565```
1566
1567![textTextSelectableMode](figures/textTextSelectableMode.gif)
1568
1569### Example 11
1570
1571This example shows how to set **editMenuOptions**.
1572
1573```ts
1574// xxx.ets
1575@Entry
1576@Component
1577struct TextExample11 {
1578  @State text: string = 'Text editMenuOptions'
1579
1580  onCreateMenu(menuItems: Array<TextMenuItem>) {
1581    menuItems.forEach((value, index) => {
1582      value.icon = $r('app.media.startIcon')
1583      if (value.id.equals(TextMenuItemId.COPY)) {
1584        value.content = "Copy"
1585      }
1586      if (value.id.equals(TextMenuItemId.SELECT_ALL)) {
1587        value.content = "Select All"
1588      }
1589    })
1590    let item1: TextMenuItem = {
1591      content: 'custom1',
1592      icon: $r('app.media.startIcon'),
1593      id: TextMenuItemId.of('custom1'),
1594    }
1595    let item2: TextMenuItem = {
1596      content: 'custom2',
1597      id: TextMenuItemId.of('custom2'),
1598      icon: $r('app.media.startIcon'),
1599    }
1600    menuItems.push(item1)
1601    menuItems.unshift(item2)
1602    return menuItems
1603  }
1604
1605  build() {
1606    Column() {
1607      Text(this.text)
1608        .fontSize(20)
1609        .copyOption(CopyOptions.LocalDevice)
1610        .editMenuOptions({
1611          onCreateMenu: this.onCreateMenu, onMenuItemClick: (menuItem: TextMenuItem, textRange: TextRange) => {
1612            if (menuItem.id.equals(TextMenuItemId.of("custom2"))) {
1613              console.log("Intercept id: custom2 start:" + textRange.start + "; end:" + textRange.end)
1614              return true;
1615            }
1616            if (menuItem.id.equals(TextMenuItemId.COPY)) {
1617              console.log("Intercept COPY start:" + textRange.start + "; end:" + textRange.end)
1618              return true;
1619            }
1620            if (menuItem.id.equals(TextMenuItemId.SELECT_ALL)) {
1621              console.log("Do not intercept SELECT_ALL start:" + textRange.start + "; end:" + textRange.end)
1622              return false;
1623            }
1624            return false;
1625          }
1626        })
1627        .margin({ top: 100 })
1628    }
1629    .width("90%")
1630    .margin("5%")
1631  }
1632}
1633```
1634
1635![textEditMenuOptions](figures/textEditMenuOptions.gif)
1636
1637### Example 12
1638
1639This example shows how to use **halfLeading**.
1640
1641```ts
1642// xxx.ets
1643@Entry
1644@Component
1645struct TextExample12 {
1646  build() {
1647    Column({ space: 10 }) {
1648      // Set whether half leading is enabled.
1649      Text('halfLeading').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%')
1650      Text("This is the text with the halfLeading set.")
1651        .lineHeight(60)
1652        .halfLeading(true)
1653        .borderWidth(1)
1654        .width('80%')
1655      Text("This is the text without the halfLeading set.")
1656        .lineHeight(60)
1657        .halfLeading(false)
1658        .borderWidth(1)
1659        .width('80%')
1660    }
1661  }
1662}
1663```
1664
1665![textHalfLeading](figures/textHalfLeading.PNG)
1666
1667### Example 13
1668
1669This example shows how to enable privacy mode, which requires widget framework support.
1670
1671```ts
1672@Entry
1673@Component
1674struct ImageExample {
1675  build() {
1676    Column({ space: 10 }) {
1677      Text("privacySensitive")
1678        .privacySensitive(true)
1679        .margin({top :30})
1680    }
1681    .alignItems(HorizontalAlign.Center)
1682    .width("100%")
1683  }
1684}
1685```
1686
1687![textPrivacySensitive](figures/textPrivacySensitive.gif)
1688