实现效果
实现思路
整个小工具放在一个自定义弹窗内,弹窗右上角是关闭按钮,中间显示格式化的计时时间,底部显示操作按钮,按钮根据状态切换开始和停止。
点击开始按钮,开始计时,按钮切换为停止按钮。
点击停止按钮,停止计时,按钮切换为开始按钮。
代码实现
以下只列出了核心代码,省略了无关的组件和样式等细节。
UI结构
Column() {
Row() {
Text(this.format(this.timeCount))
}
Row() {
if (!this.isCounting) {
Button() {
Image($r('app.media.play'))
}
.onClick(() => {
this.start()
})
} else {
Button() {
Image($r('app.media.stop'))
}
.onClick(() => {
this.stop()
})
}
}
}
timeCount:计时时间,通过format方法格式化。
isCounting:用于切换显示开始和停止按钮。
format方法中使用了dayjs库格式化时间。
timer: number | null = null
@State timeCount: number = 0
@State isCounting: boolean = false
stop = () => {
clearInterval(this.timer)
this.isCounting = false
}
start = () => {
this.stop()
this.timeCount = 0
this.isCounting = true
this.timer = setInterval(function () {
if (!this.isCounting) clearInterval(this.timer)
this.timeCount++
}.bind(this), 1)
}
format = (count): string => {
return dayjs(count).format('mm:ss:SSS')
}
至此,一个简单的计时器就做好了。
想起了高中时候,比着看谁停的离1秒最近。
完结散花
如发现文章内容有任何问题,请提出您的宝贵意见予以指正,感谢您的阅读。