DEV Community

HarmonyOS
HarmonyOS

Posted on

Wrapping Multi-Line Text Inside ArkUI Buttons: constraintSize vs width (HarmonyOS, Wearables & Phones)

Read the original article:Wrapping Multi-Line Text Inside ArkUI Buttons: constraintSize vs width (HarmonyOS, Wearables & Phones)

Wrapping Multi-Line Text Inside ArkUI Buttons: constraintSize vs width

Requirement Description

Show how to wrap multi-line text inside a Button by placing a Text component inside the button and constraining its width so the text breaks onto multiple lines (as in the provided screenshot).

Background Knowledge

  • Button can host a Text child; wrapping occurs when width is constrained: Link Link
  • Use universal attribute constraintSize to limit a child’s size during layout, which can force wrapping: Link

Implementation Steps

  1. Place a Text component inside the Button.
  2. Constrain the Text width using either:
    • constraintSize({ minWidth: W, maxWidth: W }), or
    • width(W).
  3. Keep the button larger than the constrained text area so text can wrap visibly.
  4. (Optional) Tune typography (fontSize, textAlign, maxLines) to match your UI.

Code Snippet / Configuration

Approach A — Using constraintSize (precise min/max control)

@Entry
@Component
struct Index {
  build() {
    Column() {
      Button() {
        Text('Export Report')
          .fontSize(20)
          .textAlign(TextAlign.Center)
          .constraintSize({
            minWidth: 50,
            maxWidth: 50
          })
      }
      .width(100)
      .height(100)
      .backgroundColor('#87CEEB')
      .borderRadius(60)
      .fontColor(Color.White)
    }
    .justifyContent(FlexAlign.Center)
    .width('100%')
    .height('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

Approach B — Using fixed width (simpler)

@Entry
@Component
struct Index {
  build() {
    Column() {
      Button() {
        Text('Export Report')
          .fontSize(20)
          .textAlign(TextAlign.Center)
          .width(50) // Narrower than Button to force wrapping
      }
      .width(100)
      .height(100)
      .backgroundColor('#87CEEB')
      .borderRadius(60)
      .fontColor(Color.White)
    }
    .justifyContent(FlexAlign.Center)
    .width('100%')
    .height('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

Test Results

  • Verified that long labels wrap across lines within the button, matching the expected layout.

9.png

Limitations or Considerations

  • Make sure the Button’s inner width exceeds the Text width; otherwise wrapping may not be visible.
  • Very long words may require hyphenation or manual line breaks.
  • Works for phones and wearables; for circular buttons on wearables, consider additional horizontal padding to avoid edge clipping.

Related Documents or Links

Written by Bunyamin Eymen Alagoz

Top comments (0)