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
相关产品推荐
相关产品推荐

