SwiftUI:选择器中的 ForEach 未更新 [英] SwiftUI: ForEach in Picker doesn't update

查看:25
本文介绍了SwiftUI:选择器中的 ForEach 未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元素数组,我想使用 Picker 从中选择一个元素,我有一个 Button,它只是向数组添加一个新元素.问题是,当我添加一个元素时,Picker 选项不会更新.它不适用于 DefaultPickerStyle,但适用于 SegmentedPickerStyle.

I have an array of elements, from which I want to chose one using Picker, and I have a Button which simply adds a new element to the array. The thing is, when I add an element, the Picker choices are not updated. It doesn't work with DefaultPickerStyle, but works with SegmentedPickerStyle.

代码:

import SwiftUI

struct ExampleView: View {
    @State
    var array : Array<Int> = [Int]()
    @State
    var selection : Int = 0

    var body: some View {
        VStack {
            Picker("", selection: self.$selection) {
                ForEach(self.array, id : \.self) { i in
                    Text(String(i))
                }
            }
            // uncomment, and picker will refresh upon pushing the button
            //.pickerStyle(SegmentedPickerStyle())

            Button(action: {
                self.array.append(self.array.count)
            }){
                Text("Add me: " + String(self.array.count))
            }
        }
    }
}

struct ExampleView_Previews: PreviewProvider {
    static var previews: some View {
        ExampleView()
    }
}

有什么办法可以解决这个问题吗?我真的需要更新 Picker(以其默认样式).Xcode 版本 11.2.1 (11B500).

Is there any way to fix this? I really need to update the Picker (in its default styling). Xcode Version 11.2.1 (11B500).

推荐答案

正如@e-coms 所指出的,有一个 类似问题.@p-ent (github) 是在每次按下按钮时为 Picker 重新分配一个唯一的 .id(...),以强制更新.适应我的问题:

As @e-coms pointed out, there is a similar question. An acceptable workaround found by @p-ent (github) is to re-assign a unique .id(...) for Picker on each button push, to force its update. Adapted to my question:

UPD:更好,谢谢@e-coms

UPD: even better, thanks @e-coms

import SwiftUI

struct ExampleView: View {
    @State
    var array : Array<Int> = [0,1,2]
    @State
    var selection : Int = 0

    var body: some View {
        VStack {
            Picker("", selection: self.$selection) {
                ForEach(self.array, id : \.self) { i in
                    Text(String(i))
                }
            }
            .id(self.array)

            Button(action: {
                self.array.append(self.array.count)
            }){
                Text("Add me: " + String(self.array.count))
            }
        }
    }
}

struct ExampleView_Previews: PreviewProvider {
    static var previews: some View {
        ExampleView()
    }
}

这篇关于SwiftUI:选择器中的 ForEach 未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆