0

我编写以下代码并将数据显示到滚动视图上的 Hstack

就我而言,我从服务调用中收到 10 个项目,并在 Hstack 中显示这些项目当用户第一次进入屏幕时,前 5 天可见,

但我需要先显示最后 5 个日期。

需要第一次看到最后一个索引(进入屏幕时)。

即需要先显示当前日期

HStack(alignment:.center){
                GeometryReader{ proxy in
                    ScrollView(.horizontal) {
                        
                        LazyHStack {
                            ForEach(days.indices, id: \.self) { i in
                                CalendarView(
                                    number: days[i].number,
                                    days: days[i].weekday,
                                    color: days[i].isToday ? #colorLiteral(red: 0.9060331583, green: 0.2547450066, blue: 0.3359550834, alpha: 1) : #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1),
                                    textcolor: days[i].isToday ? #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) : #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), proxy: proxy
                                )
                                .onTapGesture{
                                    print(days[i])
                                    // this is just for replacing the current selection
                                    for j in days.indices { days[j].isToday = false }
                                    days[i].isToday = true
                                }
                            }
                        }
                    }
                }
            }
            .padding([.trailing,.leading],3)
4

1 回答 1

0

使用 ScrollViewReader

HStack(alignment:.center){
    GeometryReader{ proxy in
        ScrollView(.horizontal) {
            ScrollViewReader { value in // <== Here
                LazyHStack {
                    ForEach(days.indices, id: \.self) { i in
                        CalendarView(
                            number: days[i].number,
                            days: days[i].weekday,
                            color: days[i].isToday ? #colorLiteral(red: 0.9060331583, green: 0.2547450066, blue: 0.3359550834, alpha: 1) : #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1),
                            textcolor: days[i].isToday ? #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) : #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), proxy: proxy
                        )
                        .id(i) // <== Here
                        .onTapGesture{
                            print(days[i])
                            // this is just for replacing the current selection
                            for j in days.indices { days[j].isToday = false }
                            days[i].isToday = true
                        }
                    }
                }.onAppear(){ // <== Here
                    value.scrollTo(days.count - 1) // <== Here
                }
            }
        }
    }
}
.padding([.trailing,.leading],3)
于 2021-07-07T08:17:09.750 回答