目录

TextInput组件禁止长按事件

问题现象

TextInput组件长按输入框内文本时会自动选中文本,如何实现禁止长按事件?

效果预览

背景知识

解决方案

系统长按事件触发时间为500ms,可以设置LongPressGesture长按手势事件触发时间小于500ms,实现拦截系统长按事件的效果。

@Entry
@Component
struct TextInputNoLongPress {
  @State message: string = '';

  build() {
    Column() {
      Text(`输入的内容: ${this.message}`)
        .margin({ top: 100, bottom: 30 });
      TextInput({ placeholder: '请输入内容' })
        .borderRadius(0)
        .onChange((value: string) => {
          this.message = value;
        })
        .gesture(
          LongPressGesture({ repeat: true, duration: 400 })
            // 由于repeat设置为true,长按动作存在时会连续触发,触发间隔为duration(默认值500ms)
            .onAction(() => {
              return true;
            })
            .onActionEnd(() => {
            })
        )
        .selectionMenuHidden(true);
    }
    .height('100%')
    .width('100%')
    .padding(16);
  }
}