2

我正在通过 swift & swiftui 探索我的方式,试图自学。我目前的挑战是制作一个水平日历,它在单行上滚动,一周根据需要动态添加天数。像图像这样的东西,关于从哪里开始这样的东西的任何指示?我想出了每天的单一视图元素,并通过日历日期进行某种循环以建立日历......

想做这样的事情

在日期/日历方面,我几乎是初学者。我管理了格式化/转换和添加/减去天和月的基础知识,但这几乎就是我所处的位置

我已经在 scrollView 中为当前月份的 HStack 天数设置了这个,但我不知道如何确定在 scrollView 的中心可见哪个子视图 - 部分是为了能够更新月份名称。

struct SingleCalendarView: View {
@State var monthString: String = "Not Set"

let calendar = Calendar.current

//var day:[Date]
var body: some View {
    let dates = getWeek()

    VStack {
        Text(getMonth(date: Date()))
        ScrollView(.horizontal) {
           HStack {
                ForEach(dates, id: \.self) { day in
                        VStack {
                            Text(getDayShort(date: day))
                                .font(.title3)
                            Text("\(getDayNumber(date: day))")
                                .font(.largeTitle)
                        }
                        .frame(width: 100, height: 100)
                    }
            }
        }
    }
}
func getMonth(date: Date) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "LLLL"
    return dateFormatter.string(from: date)
}

func getDayShort(date: Date) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "E"
    return dateFormatter.string(from: date)
}

func getDayNumber(date: Date) -> Int {
    let calendar = Calendar.current
    let components = calendar.dateComponents([.day], from: date)
    return components.day ?? 0
}

func getWeek() -> [Date] {
    let currentDate = Date()

    let calendar = Calendar.current
    let dayOfWeek = calendar.component(.weekday, from: currentDate)
    
    let range = calendar.range(of: .day, in: .month, for: currentDate)!
    
    let daysMonth = (range.lowerBound ..< range.upperBound)
        .compactMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: currentDate) }
    
    return daysMonth
}
}
4

0 回答 0