DEV Community

HarmonyOS
HarmonyOS

Posted on

How to Limit the Number of Lines Displayed for the Placeholder Property of the RichEditor Component?

Read the original article:How to Limit the Number of Lines Displayed for the Placeholder Property of the RichEditor Component?

Question

How to Limit the Number of Lines Displayed for the Placeholder Property of the RichEditor Component?

Short Answer

Use a Stack container with a Text component to simulate the placeholder effect with the following steps:

  1. Overlay Components: Place RichEditor and Text inside a Stack to layer the placeholder text over the editor.
  2. Text Truncation:
    • Set maxLines(1) to restrict the text to one line.
    • Use textOverflow({ overflow: TextOverflow.Ellipsis }) to truncate excess text with ellipsis.
  3. Event Handling:
    • Monitor onEditingChange to hide the placeholder when the user starts editing.
    • Use hitTestBehavior(HitTestMode.Transparent) to ensure the Text does not block user interactions with the RichEditor.

Here you can find the related code example:

@Entry
@Component
struct Index {
  tips: string = 'This is sample text, with any excess truncated. Here is the sample text, with ellipses displayed for any excess.';
  controller: RichEditorController = new RichEditorController();
  options: RichEditorOptions = { controller: this.controller };
  @State flag: boolean = false

  build() {
    Column() {
      Stack() {
        RichEditor(this.options)
          .onEditingChange((isEditing: boolean) => {
            this.flag = isEditing
          })
          .width(300)
          .height(300)

        Text(`${!this.flag && (this.controller.getSpans()).length < 1 ? this.tips : ''}`)
          .width(250) // Set text box width
          .maxLines(1) // Limit display to one line
          .textOverflow({ overflow: TextOverflow.Ellipsis }) // Hide excess text
          .border({ width: 5 })
          .hitTestBehavior(HitTestMode.Transparent)
          .fontColor(Color.Gray)
          .border({
            width: 0
          })
          .position({
            top: 0,
            left: 0
          })
      }
    }.height('100%').width('100%')
    .justifyContent(FlexAlign.Center)
  }
}
Enter fullscreen mode Exit fullscreen mode

Applicable Scenarios

  • Rich Text Editing (Content Creation)
  • Messaging and Communication Apps
  • Form Inputs with Enhanced Text Fields

Written by Mehmet Algul

Top comments (0)