_xiaofang/xiaofang/Assets/Script/UI/PanelUI/CalendarPanel.cs
2024-11-29 09:47:47 +08:00

82 lines
2.3 KiB
C#

using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CalendarPanel : MonoBehaviour
{
[Header("组件")]
public Text monthText; // 当前月份显示的Text
public Transform dateGrid; // 用于显示日期的GridLayoutGroup
public GameObject dayButtonPrefab; // 日期按钮的预制体
public Button prevMonthBtn; // 上一个月按钮
public Button nextMonthBtn; // 下一个月按钮
public Text selectedDateText; // 显示选中的日期
public DateTime currentDate; // 当前显示的日期
// Start is called before the first frame update
void Start()
{
currentDate = DateTime.Now; // 初始显示当前日期
UpdateCalendar();
//prevMonthBtn.onClick.AddListener(OnPrevMonth);
//nextMonthBtn.onClick.AddListener(OnNextMonth);
}
// 更新日历面板
void UpdateCalendar()
{
// 更新月份显示
monthText.text = currentDate.ToString("yyyy年MM月");
// 清空日期按钮之前,先确保日期按钮的销毁没有问题
foreach (Transform child in dateGrid)
{
Destroy(child.gameObject); // 销毁所有子物体(日期按钮)
}
// 获取当前月份的第一天
DateTime firstDayOfMonth = new DateTime(currentDate.Year, currentDate.Month, 1);
// 获取该月份的总天数
int daysInMonth = DateTime.DaysInMonth(currentDate.Year, currentDate.Month);
// 获取第一天是星期几
int firstDayOfWeek = (int)firstDayOfMonth.DayOfWeek; // 0是星期日, 6是星期六
// 生成空的占位符,填充前面几天
for (int i = 0; i < firstDayOfWeek; i++)
{
GameObject emptyItem = Instantiate(dayButtonPrefab, dateGrid);
emptyItem.SetActive(false); // 隐藏这些占位符
}
// 生成当前月份的每一天
for (int day = 1; day <= daysInMonth; day++)
{
GameObject dayItem = Instantiate(dayButtonPrefab, dateGrid);
Button dayButton = dayItem.GetComponent<Button>();
Text dayText = dayItem.GetComponentInChildren<Text>();
dayText.text = day.ToString();
}
}
// 上一个月
public void OnPrevMonth()
{
currentDate = currentDate.AddMonths(-1);
UpdateCalendar();
}
// 下一个月
public void OnNextMonth()
{
currentDate = currentDate.AddMonths(1);
UpdateCalendar();
}
}