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

SwiftUI中@Binding值变更时视图未更新的问题

SwiftUI中@Binding值变更时视图未更新的问题

嘿,刚上手SwiftUI遇到这种视图不更新的情况太正常啦!我帮你捋捋代码里的问题~

首先看你没写完的ItemGridView代码,你在onTapGesture里只写了select...,但核心的一步你没做:点击的时候把绑定的selectedItem更新为当前点击的item!这就导致ContentView里的@State var item根本没变化,ItemView的isSelected自然不会跟着变,UI当然没反应啦。

先把ItemGridView里的点击事件补全:

struct ItemGridView: View {
    @Binding var selectedItem: MyItem

    var body: some View {
        LazyVGrid(columns: [GridItem(), GridItem(), GridItem()]) {
            ForEach(MyItem.allCases) { item in
                ItemView(name: item.name,
                         isSelected: item == self.selectedItem)
                .onTapGesture {
                    // 关键:更新绑定的selectedItem为当前点击的item
                    self.selectedItem = item
                }
            }
        }
    }
}

接下来还要确认两个点,避免踩坑:

  • 你的MyItem枚举必须同时遵循CaseIterable和Identifiable协议,不然ForEach(MyItem.allCases)会报错,而且要保证id是唯一的(用枚举本身当id就很合适),比如:
enum MyItem: CaseIterable, Identifiable {
    case first, second, third, fourth, fifth, sixth
    // 遵循Identifiable
    var id: MyItem { self }
    // 每个case对应的名称
    var name: String {
        switch self {
        case .first: return "First"
        case .second: return "Second"
        case .third: return "Third"
        case .fourth: return "Fourth"
        case .fifth: return "Fifth"
        case .sixth: return "Sixth"
        }
    }
}
  • 你的ItemView要真的根据isSelected的值来更新UI,不能只是传了这个参数但没用到它。比如给选中的item加个背景色或者边框,示例代码如下:
struct ItemView: View {
    let name: String
    let isSelected: Bool
    
    var body: some View {
        Text(name)
            .padding()
            .background(isSelected ? Color.blue : Color.gray.opacity(0.3))
            .foregroundColor(isSelected ? .white : .black)
            .cornerRadius(8)
    }
}

这样修改之后,当你点击某个ItemView时,selectedItem会被更新,ItemView的isSelected参数会跟着变化,对应的UI(比如背景色)就会立刻更新啦!

备注:内容来源于stack exchange,提问作者Filipe Ramos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.17 10:10:30