You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中如何通过按钮重置ScrollView及ForEach循环相关状态?

SwiftUI 重置功能实现方案

要实现重置功能,需要同时重置状态变量和ScrollView的滚动位置,具体修改如下:

修改后的完整代码

import SwiftUI

struct ContentView: View {
    let columns = [
        GridItem(.flexible()),
        GridItem(.flexible()),
        GridItem(.flexible()),
        GridItem(.flexible()),
        GridItem(.flexible())
    ]    
    @State private var amount = 10 // 修正变量名拼写错误
    @State private var angle = 0.0
    
    var body: some View {
        ScrollViewReader { proxy in // 添加ScrollViewReader控制滚动位置
            ScrollView {
                LazyVGrid(columns: columns, spacing: 15) {
                    ForEach(0..<20) { number in
                        Rectangle()
                            .foregroundColor(Color.red)
                            .frame(width: 50, height: 80)
                            .cornerRadius(10)
                            .shadow(color: .black, radius: 5, x: 2, y: 2)
                            .rotationEffect(.degrees(angle))
                            .overlay(
                                Text("\(number)").foregroundColor(.white)
                            )
                            .onTapGesture {
                                amount += number
                                angle += 5
                            }
                    }
                }
                .padding(.all, 10)
                .id("gridTop") // 给网格添加唯一ID,用于滚动定位
                
                Text ("Total Amount is : \(amount)")
                    .font(.system(size: 20))
                    .bold()
                    .padding()
                
                Button {
                    // 重置所有状态变量
                    amount = 10
                    angle = 0.0
                    // 让ScrollView滚动回顶部
                    withAnimation {
                        proxy.scrollTo("gridTop", anchor: .top)
                    }
                } label: {
                    Text("Reset")
                        .font(.system(size: 16))
                        .bold()
                        .foregroundColor(Color.blue)
                }
            }
        }
    }
}

关键修改说明

  • 状态变量重置:在按钮的action闭包中,直接将amount和angle设回初始值,所有矩形的旋转角度和累计金额会立即恢复初始状态。
  • ScrollView滚动重置:通过ScrollViewReader获取滚动代理,给LazyVGrid添加唯一ID,调用proxy.scrollTo方法让ScrollView滚动到网格顶部,完成视觉上的重置。
  • 变量名规范修正:将原代码中的Amout改为符合Swift命名规范的amount,避免拼写错误。

内容的提问来源于stack exchange,提问作者Sunny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 16:20:42