当 Picker selectedValue 更改时,SwiftUI 2.0 App 崩溃

Posted

技术标签:

【中文标题】当 Picker selectedValue 更改时,SwiftUI 2.0 App 崩溃【英文标题】:SwiftUI 2.0 App crash when Picker selectedValue changed 【发布时间】:2021-02-18 11:21:01 【问题描述】:

你好,这是我的示例代码

import SwiftUI

final class ViewModel: ObservableObject 
    @Published var countries: [Country?] = [
        Country(id: 0, name: "country1", cities: ["c1 city1", "c1 city2", "c1 city3"]),
        Country(id: 1, name: "country2", cities: ["c2 city1", "c2 city2", "c2 city3"]),
        Country(id: 2, name: "country3", cities: ["c3 city1", "c3 city2", "c3 city3"])
    ]


struct ContentView: View 
    
    @ObservedObject var viewModel = ViewModel()
    @State private var selectedCountry: Country? = nil
    @State private var selectedCity: String? = nil
    
    var body: some View 
        VStack 
            Picker("", selection: $selectedCountry) 
                ForEach(viewModel.countries, id: \.self)  country in
                    Text(country!.name).tag(country)
                
            
            .pickerStyle(SegmentedPickerStyle())
            Text(selectedCountry?.name ?? "no selection")
            
            if selectedCountry != nil 
                Picker("", selection: $selectedCity) 
                    ForEach(selectedCountry!.cities, id: \.self)  city in
                        Text(city!).tag(city)
                    
                
                .pickerStyle(SegmentedPickerStyle())
                Text(selectedCity ?? "no selection")
            
        
        .padding()
    


struct ContentView_Previews: PreviewProvider 
    static var previews: some View 
        ContentView()
    


struct Country: Codable, Hashable, Identifiable 
    var id: Int
    var name: String
    var cities: [String?]

it works at first but when select a country then select another country then go back to the first choice it crashes, 我正在使用最新的 Xcode beta 我不知道这是原因还是我的方法是错误的 谢谢

【问题讨论】:

更新:我刚刚在live Xcode版本上尝试过,同样的问题发生了,所以不是beta引起的 【参考方案1】:

问题出在缓存绑定中。如果数据源发生变化,我们需要重新创建选择器。

在下面找到一个修复。使用 Xcode 12.4 / ios 14.4 测试

if selectedCountry != nil 
    Picker("", selection: $selectedCity) 
        ForEach(selectedCountry!.cities, id: \.self)  city in
            Text(city!).tag(city)
        
    
    .pickerStyle(SegmentedPickerStyle())
    .id(selectedCountry!)                // << here !!

    Text(selectedCity ?? "no selection")

【讨论】:

以上是关于当 Picker selectedValue 更改时,SwiftUI 2.0 App 崩溃的主要内容,如果未能解决你的问题,请参考以下文章

iOS 15 SwiftUI 3 Picker 绑定在更改@State 值后不起作用

获取 DataGridViewComboboxColumn SelectedValue (VB.Net)

在 UI Picker View Swift 中重新加载组件

在 SwiftUI 中,我如何知道 Picker 选择何时更改?为啥 didSet 不起作用?

SwiftUI Picker 在同一视图中更改第二个状态变量

更改默认的 React Native <Picker> 下拉箭头图标