目录

输入框获焦时不显示光标

问题现象

打开应用,点击搜索,输入框没有光标。

背景知识

问题定位

  1. 使用DevEco Testing查看问题组件,该组件为TextInput组件。

  2. 全局搜索caretColor,排查输入框光标颜色设置。
    • 颜色设置为#0C000000,与搜索框背景色一致。
      @Entry
      @Component
      struct Index {
        build() {
          Column() {
            TextInput({ placeholder: '请输入搜索内容' })
              .fontSize(14)
              .fontWeight(FontWeight.Bold)
              .backgroundColor('#f1f3f5')
              .placeholderFont({
                size: 14,
                weight: 400
              })
              .caretColor('#0C000000')
              .height(40)
              .enableKeyboardOnFocus(true)
              .width('80%')
              .margin({ top: 20 })
          }
          .height('100%')
          .width('100%');
        }
      }
    • 颜色设置为#00000000,文字颜色完全透明。
      @Entry
      @Component
      struct Index {
        build() {
          Column() {
            TextInput({ placeholder: '请输入搜索内容' })
              .fontSize(14)
              .fontWeight(FontWeight.Bold)
              .backgroundColor('#f1f3f5')
              .placeholderFont({
                size: 14,
                weight: 400
              })
              .caretColor('#00000000')
              .height(40)
              .enableKeyboardOnFocus(true)
              .width('80%')
              .margin({ top: 20 });
          }
          .height('100%')
          .width('100%');
        }
      }

分析结论

光标颜色设置不合理,导致光标不显示。

修改建议

合理设置光标颜色,如黑色不透明。

@Entry
@Component
struct TextInputCaretColor {
  build() {
    Column() {
      TextInput({ placeholder: '请输入搜索内容' })
        .fontSize(14)
        .fontWeight(FontWeight.Bold)
        .backgroundColor('#f1f3f5')
        .placeholderFont({
          size: 14,
          weight: 400
        })
        .caretColor('#000000') // 黑色不透明
        .height(40)
        .enableKeyboardOnFocus(true)
        .width('80%')
        .margin({ top: 20 });
    }
    .height('100%')
    .width('100%');
  }
}

效果图如下: