首页 > 解决方案 > 如何在 Hstack scrollview swiftUI 中将最后一个索引设为初始值

问题描述

我编写以下代码并将我的天数数组显示到 Hstack 滚动视图中。

我想通过使用 ScrollViewReader 使用 scrollProxy 滚动按钮操作

我实现如下

当我进行左右按钮操作时,它按预期工作

但是当我进入屏幕最初显示最后一个索引但它不适合我

任何人都知道移动最后一个索引的正确位置。

var body: some View {
        
        ScrollViewReader { scrollProxy in
            ZStack{
                VStack {
                    
                    Button(action:{
                        scrollProxy.scrollTo(selectedDay) //<----  Working
                    })
                        .padding(.leading, 10)
                    Spacer()
                    ScrollView(.horizontal, showsIndicators: false){
                        HStack(spacing: 20) {
                            ForEach(days.indices, id: \.self) { i in
                                CalendarView(
                                    number: self.days[i].number,
                                    days: self.days[i].weekday,
                                    color: self.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: self.days[i].isToday ? #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) : #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
                                )
                                    .onTapGesture{
                                        print(self.days[i])
                                        // this is just for replacing the current selection
                                        for j in self.days.indices { self.days[j].isToday = false }
                                        self.days[i].isToday = true
                                }
                            }}
                            .padding(.leading,10)
                            .padding(.bottom, 10)
                            .shadow(radius: 3, x: 3, y: 3)
                    }
                    Spacer()
                    Button(action:{
                        scrollProxy.scrollTo(selectedDay) //<--   Working
                    })
                        .padding(.leading)
                    Spacer()
                    
                }
            }
            .onAppear {
                self.getCurrentWeekdays()
                scrollProxy.scrollTo(days.count - 1)  //<--  Here it is not Work.
             }
        }
    }

标签: iosswiftswiftuiscrollview

解决方案


推荐阅读