SwiftUI中@State修饰的index变量状态无法更新如何解决
问题根因
@State是SwiftUI专属的状态属性包装器,只有当所属结构体遵守View协议、被SwiftUI的视图渲染系统托管时,它的状态更新逻辑才会生效。
你当前定义的idontcare只是个普通结构体,没有遵守View协议,里面的@State var index本质上就是个初始值为0的普通变量,不会建立任何状态绑定关系,闭包里的赋值操作不会触发状态持久化更新,所以打印永远返回初始值0。
修复步骤
- 给
idontcare结构体添加View协议遵守,实现必须的body属性,把showMenu()返回的内容挂到body上,让SwiftUI接管这个结构体的状态管理 - 原代码里ForEach直接遍历按钮字符串,拿不到每个按钮对应的索引,写死赋值为5本身也不符合“按不同按钮更新对应index”的需求,换成带索引的遍历方式即可
- 如果需要在赋值后立刻拿到最新的index值,把打印逻辑放到主线程异步调度块里,避免同步执行时取到状态更新前的旧值
修复后可运行代码
import SwiftUI struct idontcare: View { @State var index: Int = 0 let buttons: [String] = [ "Primary", "Blue", "Green", "Red", "Yellow", "Orange","Gray", "Purple", "Cyan", "Pink", "Teal"] let buttonColor: [Color] = [Color.primary, Color.blue, Color.green, Color.red, Color.yellow, Color.orange, Color.gray, Color.purple, Color.cyan, Color.pink, Color.teal] var body: some View { showMenu() } func showMenu() -> some View{ Menu("Update Color: "){ ForEach(Array(buttons.enumerated()), id: \.element) { idx, button in Button(action: { self.index = idx DispatchQueue.main.async { print(self.index) } }) { Label(button, systemImage: "paintbrush.pointed") } } } } }
内容的提问来源于stack exchange,提问作者Aleck
相关产品推荐
相关产品推荐

