
前言
在日历应用中,月份切换是最基本的交互。"海风日记"的日历页通过左右箭头按钮实现月份切换,同时支持"今天"按钮快速回到当月。
本文将从源码出发,深入讲解月份切换的逻辑实现和边界处理。
一、月份切换实现
1.1 状态变量
typescript
@Component
export struct CalendarTab {
@State curYear: number = new Date().getFullYear()
@State curMonth: number = new Date().getMonth() // 0-indexed
private todayDate = new Date().getDate()
private todayMonth = new Date().getMonth()
private todayYear = new Date().getFullYear()
}
1.2 上个月
typescript
private prevMonth() {
if (this.curMonth === 0) {
this.curYear -= 1 // 跨年
this.curMonth = 11 // 十二月
} else {
this.curMonth -= 1
}
}
1.3 下个月
typescript
private nextMonth() {
if (this.curMonth === 11) {
this.curYear += 1 // 跨年
this.curMonth = 0 // 一月
} else {
this.curMonth += 1
}
}
二、导航按钮
typescript
Row({ space: 12 }) {
// 左箭头
Button() {
SymbolGlyph($r('sys.symbol.chevron_left')).fontSize(16).fontColor([COLOR_TEXT_MAIN])
}
.backgroundColor('transparent').width(36).height(36)
.onClick(() => { this.prevMonth() })
// 月份标题
Column({ space: 2 }) {
Text(this.getMonthName(this.curMonth))
.fontSize(22).fontColor(COLOR_TEXT_MAIN).fontWeight(FontWeight.Bold)
Text(`${this.curYear}年`).fontSize(12).fontColor(COLOR_TEXT_SECONDARY)
}
.alignItems(HorizontalAlign.Center)
// 右箭头
Button() {
SymbolGlyph($r('sys.symbol.chevron_right')).fontSize(16).fontColor([COLOR_TEXT_MAIN])
}
.backgroundColor('transparent').width(36).height(36)
.onClick(() => { this.nextMonth() })
}
三、"今天"按钮
typescript
Button('今天')
.height(30).fontSize(13).fontColor('#FFFFFF').fontWeight(FontWeight.Bold)
.backgroundColor(COLOR_PRIMARY).borderRadius(15)
.padding({ left: 12, right: 12 })
.onClick(() => {
this.curYear = this.todayYear
this.curMonth = this.todayMonth
})
四、年视图的年份导航
typescript
Row({ space: 4 }) {
Button() {
SymbolGlyph($r('sys.symbol.chevron_left')).fontSize(16).fontColor([COLOR_AMBER])
}
.backgroundColor('transparent').width(36).height(36)
.onClick(() => { this.curYear -= 1 })
Button() {
SymbolGlyph($r('sys.symbol.chevron_right')).fontSize(16).fontColor([COLOR_AMBER])
}
.backgroundColor('transparent').width(36).height(36)
.onClick(() => { this.curYear += 1 })
}
五、常见问题
5.1 月份切换后 UI 不更新
问题:点击切换按钮后,月份数字没有变化。
原因 :@State 变量更新了但 UI 未重新渲染。
解决方案 :确保 curYear 和 curMonth 是 @State 变量。
总结
本文通过"海风日记"的日历页,深入讲解了月份切换的实现:
- prevMonth/nextMonth:月份切换逻辑
- 跨年处理:边界情况处理
- "今天"按钮:快速回到当月
- 年视图导航:年份切换
下一篇文章将深入讲解 月统计面板,敬请期待。
如果这篇文章对你有帮助,欢迎点赞👍、收藏⭐、关注🔔,你的支持是我持续创作的动力!
相关资源: