HarmonyOS 鸿蒙Next中TextInput限制32字节该如何设置?

HarmonyOS 鸿蒙Next中TextInput限制32字节该如何设置?

限制 TextInput 的字数限制的时候可以设置 .maxLength(32) 也可以 this.TextInput.length < 32

但是我现在业务逻辑为限制 字节 长度,并不是字符长度,限制32字节 该如何实现?

3 回复

可以参考:

@Entry
@Component
struct Page4 {
  @State private text:string = '';
  @State private lastText:string = '';
  getByteLength(str:string) {
    let byteLength = 0;
    for (let i = 0; i < str.length; i++) {
      const charCode = str.charCodeAt(i);
      if (charCode <= 0xff) {
        byteLength += 1;
      } else {
        byteLength += 2;
      }
    }
    return byteLength;
  }
  build() {
    RelativeContainer() {
      TextInput({text:this.text})
        .onChange((value: string) => {
          let num = this.getByteLength(value)
          console.log('num -',num);
          if (num > 32) {
            this.text = ' '
            this.text = this.lastText
          } else{
            this.lastText = value
            this.text = value
          }
        })
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
    }
    .height('100%')
    .width('100%')
  }
}
  • 以上是初步分析结论,如有疑问可以展开回复,看到后会继续协助定位阻碍点。
  • 开源网站上收录了UI、系统接口、Web、创新特性等场景化鸿蒙示例DEMO,开发中可以参考:https://gitee.com/scenario-samples/demo-index

更多关于HarmonyOS 鸿蒙Next中TextInput限制32字节该如何设置?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中限制TextInput输入32字节:

  1. 使用onChange监听输入变化
  2. 通过TextInputController获取当前文本
  3. 计算UTF-8编码字节数
  4. 超出时截断文本或阻止输入

关键代码示例:

@State inputText: string = ''
controller: TextInputController = new TextInputController()

onTextChange(text: string) {
  const byteLength = new TextEncoder().encode(text).length
  if(byteLength <= 32) {
    this.inputText = text
  } else {
    this.controller.setText(this.inputText)
  }
}

使用TextEncoder API精确计算字节数。

在HarmonyOS Next中,要限制TextInput的字节数为32字节,可以通过监听输入变化并计算字节数来实现。以下是实现方案:

  1. 使用TextInput的onChange事件监听输入变化:
@State text: string = ''

TextInput({ placeholder: '请输入' })
  .onChange((value: string) => {
    const byteLength = this.getByteLength(value)
    if (byteLength > 32) {
      // 截取符合字节长度的内容
      this.text = this.truncateToByteLength(value, 32)
    } else {
      this.text = value
    }
  })
  1. 添加字节计算和截取方法:
// 计算字符串字节长度
private getByteLength(str: string): number {
  let length = 0
  for (let i = 0; i < str.length; i++) {
    const charCode = str.charCodeAt(i)
    length += charCode > 255 ? 2 : 1 // 中文等占2字节,英文占1字节
  }
  return length
}

// 截取到指定字节长度
private truncateToByteLength(str: string, maxBytes: number): string {
  let result = ''
  let bytes = 0
  
  for (let i = 0; i < str.length; i++) {
    const char = str.charAt(i)
    const charBytes = str.charCodeAt(i) > 255 ? 2 : 1
    
    if (bytes + charBytes > maxBytes) {
      break
    }
    
    result += char
    bytes += charBytes
  }
  
  return result
}

这种方法可以准确计算中英文混合输入的字节数,并在超过32字节时自动截断。注意要同时处理用户粘贴内容的情况。

回到顶部