|
本帖最后由 周芳木_Devlin 于 2023-7-31 15:56 编辑
1、实现功能与原理
- 九宫格图案的方式输入密码,用于密码验证场景
- 密码正确可进入,密码错误则提示
- 可以进行密码重设
ArkUI 开发框架提供了图案密码锁组件,接口:PatternLock(controller?: PatternLockController)
通过接口实现可以完成密码锁功能开发。
2、示例代码
@Entry
@Component
struct CodeLockTest {
private PatternLockController = new PatternLockController()
@State tipMessage: string = 'please input the password.'
password: number[] = [3, 4, 5] //密码存储及初始密码
passwordTem: number[] = [] //密码临时存储变量
PatternLockRest: Boolean = false //是否进入密码重设状态标识
build() {
Column() {
//密码输入提示文本
Row() {
Text(this.tipMessage)
.fontColor(Color.Blue)
.fontSize(25)
.textAlign(TextAlign.Center)
}.width('100%')
.height(60)
.margin({ top: 100 })
.justifyContent(FlexAlign.Center)
//密码锁组件
Column() {
PatternLock(this.PatternLockController)
.circleRadius(16)
.regularColor(Color.Blue)
.sideLength(350)
.selectedColor(Color.Orange)
.activeColor(Color.Red)
.pathColor(Color.Green)
.pathStrokeWidth(34)
.onPatternComplete((input: Array<number>) => {
//检测输入密码位数是否达到最少位数
if (input === null || input === undefined || input.length < 3) {
this.tipMessage = 'The password length needs to be greater than 3.'
return
}
else {
//判断锁的模式状态
if (this.PatternLockRest) {
if (this.passwordTem.length === 0) {
this.passwordTem = input
this.tipMessage = 'try again'
return
}
//密码重设时的密码二次确认
else {
if (this.passwordTem.toString() === input.toString()) {
this.password = input
this.tipMessage = 'set password' + input.toString() + ' successfully '
}
else {
this.tipMessage = 'set password failed '
}
//退出密码重设状态
this.PatternLockRest = false
}
}
else {
if (this.password.toString() === input.toString()) {
this.tipMessage = 'The password is Right,welcome! '
} else {
this.tipMessage = 'The password is Error,try again.'
}
}
}
})
}.margin({ top: 10 })
//密码重设按钮,按下进入密码重设状态
Button("Reset PatternLock")
.width(250)
.height(50)
.fontSize(25)
.margin({ top: 50 })
.onClick(() => {
this.PatternLockController.reset()
this.tipMessage = 'please input the password.'
this.PatternLockRest = true
this.passwordTem = []
})
}.width('100%')
.height('100%')
.alignItems(HorizontalAlign.Center)
}
}
3、实现效果
详见附件连接
参考资料:https://docs.openharmony.cn/pages/v4.0/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-patternlock.md/
|
|