您好,我在swiftUI中创建了一个 Select 器,用户必须接受 Select 器上的更改.

它工作得很好,但有一个问题.如果用户 Select 某个内容,然后拒绝更改,则显示的值仍将是所选的值,尽管实际值没有更改.

如果我在没有 Select 任何内容的情况下再次打开选取器,它会恢复到正确的值,但如何在不打开选取器的情况下执行此操作?

struct ContentView: View {
@State private var selectedColorIndex = "cd"
@State private var temp = ""
@State var alert = false

private var colors = ["ab", "cd", "ef", "gh", "ij", "kl", "mn", "op", "qr", "st", "uv", "wx", "yz"]
var body: some View {
    
    
    HStack {
        Text("Location")
        Picker("Location", selection: Binding(get: {selectedColorIndex}, set: {
            temp = $0
            alert = true
        })) {
            ForEach(colors, id: \.self) {
                Text($0)
            }
        }.pickerStyle(MenuPickerStyle())
        
    }.alert(isPresented: $alert) {
        Alert(title: Text("are you sure"), primaryButton: .default(Text("yes"), action: {
            selectedColorIndex = temp
            
            
        }), secondaryButton: .default(Text("no"), action: {
            
            //change shown value back to prev selectedColorIndex
        }))
    }
    
}

}

推荐答案

这不起作用,因为PickerView不会使用从绑定获得的值刷新.在绑定中添加print语句可以确认它确实提供了正确的值.

一个简单的解决方案是,每次重新判断ContentView的主体时,强制 Select 器刷新自己.我们可以通过手动更改Picker中的id来实现这一点.

var body: some View {
    HStack {
        Text("Location")
        Picker("Location", selection: Binding(get: {selectedColorIndex}, set: {
            temp = $0
            alert = true
        })) {
            ForEach(colors, id: \.self) {
                Text($0)
            }
        }
        .id(UUID()) // add this
        .pickerStyle(MenuPickerStyle())
            
        
    }.alert(isPresented: $alert) {
        Alert(title: Text("are you sure"), primaryButton: .default(Text("yes"), action: {
            selectedColorIndex = temp
            
            
        }), secondaryButton: .default(Text("no"), action: {
            // No code needed here
            //change shown value back to prev selectedColorIndex
        }))
    }
}

如果你想知道更多的原因,你可以阅读我的答案:more info

Swift相关问答推荐

如何在Swift 中创建移动的uil标签?

如何更新Square Order?

插入/删除视图时的Swiftui动态过渡

在不传递参数的情况下使用Init方法?

可以';t在标记为@Observable的类上使用属性包装

物理主体未与 spritekit Swift 的网格图案上的纹理图像对齐

允许视图在视图内更改

如何在 Swift 中做类型安全的索引?

在 init(from decoder: Decoder) 方法中访问原始 JSON 数据

仅当 boolean 为真时才实现方法(application:didReceiveRemoteNotification)

SwiftUI 动画的范围

UIButton 配置不更新按钮标题

为什么 SwiftUI 不在工具栏菜单中反映 @State 属性值?

类型 '()' 不能符合 View (除非它肯定是 View,这次没有恶作剧)

令人满意的 var body:协议扩展中的一些视图

Swift:withCheckedContinuation 和 Dispatch QoSClass

`IndexSet` 永远不会是空的?

如何在界面生成器中创建 UILayoutGuide?

Swift 中的 PageViewController 当前页面索引

如何停止 NSTimer.scheduledTimerWithTimeInterval