import ArrayList from '@ohos.util.ArrayList'
import inputMethod from '@ohos.inputMethod'
import { ZyVerText } from './ZyVerText'
@Observed
export class CodeBean {
constructor(index: number) {
this.index = index
}
code: string = ""
index: number = 0
currentIndex: number = -1;
}
//验证码输入框
@Component
export struct ZyVerCodeView {
private onInputComplete?: (content: string) => void
@Link realCode: String //输入的真正字符
@State codeData: CodeBean[] = [new CodeBean(0), new CodeBean(1), new CodeBean(2), new CodeBean(3), new CodeBean(4), new CodeBean(5)] //被显示的字符
build() {
Stack() {
Grid() {
ForEach(Array.from(this.codeData), (item: CodeBean, index) => {
GridItem() {
ZyVerText({
code: this.codeData[index]
})
}
}, (item: CodeBean, index) => index + ""
)
}.columnsGap(8)
.width('100%')
.layoutDirection(GridDirection.Row)
.columnsTemplate('1fr 1fr 1fr 1fr 1fr 1fr')
TextInput()
.opacity(0)
.id("input")
.type(InputType.Number)
.maxLength(6)
.onChange(value => {
//输入内容变化时,更新变量
for (let i = 0; i < 6; i++) {
let str = ""
if (value.length > i) {
str = value.charAt(i)
}
this.realCode = value
this.codeData[i].code = str
this.codeData[i].currentIndex = value.length
}
if (value.length == 6 && this.onInputComplete != undefined) {
this.onInputComplete(value)
}
})
.onFocus(() => {
//获取焦点
let currentIndex = (this.realCode == null ? 0 : this.realCode.length)
for (let i = 0; i < 6; i++) {
this.codeData[i].currentIndex = currentIndex
}
})
.onBlur(() => {
//失去焦点
for (let i = 0; i < 6; i++) {
this.codeData[i].currentIndex = -1
}
})
}.height(56)
}
}
//验证码弹框内小方框
import { CodeBean } from './ZyVerCodeView';
//验证码输入框的小方块
@Preview
@Component
export struct ZyVerText {
@ObjectLink @Watch('onInutChange')code: CodeBean
private intervalId: number = -1; //定时器ID
@State @Watch('onAnimation') highLight: boolean = false;
@State hide: boolean = true
//光标闪烁
onAnimation() {
clearInterval(this.intervalId)
if (!this.highLight) return
this.intervalId = setInterval(() => {
this.hide = this.hide === true ? false : true
}, 700)
console.log("onAppear")
}
onInutChange() {
if (this.code.index == this.code?.currentIndex) {
this.highLight = true
} else {
this.highLight = false
}
}
build() {
Stack() {
Text(this.code?.code)
.textAlign(TextAlign.Center)
.fontSize(27)
.height('100%')
.width('100%')
.borderWidth(1)
.borderColor(this.highLight ? 0x0056ff : 0xb5bcc9)
.borderRadius(8)
if (this.highLight && this.hide) {
Divider()
.vertical(true)
.height(32)
.strokeWidth(2)
.lineCap(LineCapStyle.Round)
.color(0x0056ff)
}
}
}
}
@Entry
@Component
struct VerifyCodePage {
@State message: string = 'Hello World';
@State verifyCode:string = ''
onInputComplete = (content:string)=>{//输入完成
this.verifyCode =content
}
build() {
Column() {
ZyVerCodeView({
realCode:this.verifyCode,
onInputComplete:this.onInputComplete
})
}
.height('100%')
.width('100%')
}
}