从 json 填充选择器,SwiftUI

Posted

技术标签:

【中文标题】从 json 填充选择器,SwiftUI【英文标题】:Filling picker from json, SwiftUI 【发布时间】:2019-12-03 05:31:22 【问题描述】:

有json(链接如下),你需要把里面的数据放到picker swiftui中,可以吗?

这是加载必要数据的类。

class pickerAPI: ObservableObject 

    @Published var groupModel: GroupModel = [GroupModelElement]()

    init() 
        loadPickerData()
    

    func loadPickerData() 
        guard let url: URL = URL(string: "https://gist.githubusercontent.com/lisindima/a3246c9eebae2e152c1f8211d10d4255/raw/30ee8647261b839c3a00024a851a340295300787/group") else  return 
        URLSession.shared.dataTask(with: url)  (data, response, error) in
            do 
                guard let json = data else  return 
                let swift = try JSONDecoder().decode(GroupModel.self, from: json)
                DispatchQueue.main.async 
                    self.groupModel = swift
                    print(self.groupModel)
                
            
            catch 
                print(error)
            
        
        .resume()
    

public struct GroupModelElement: Codable, Hashable 
    public let startYear: Int?
    public let name: String?
    public let facultyID: String?
    public let specialityID: String?
    public let groupBr: Int?
    public let id: String?

    enum CodingKeys: String, CodingKey 
        case startYear
        case name
        case facultyID
        case specialityID
        case groupBr
        case id
    

    public init(startYear: Int?, name: String?, facultyID: String?, specialityID: String?, groupBr: Int?, id: String?) 
        self.startYear = startYear
        self.name = name
        self.facultyID = facultyID
        self.specialityID = specialityID
        self.groupBr = groupBr
        self.id = id
    


public typealias GroupModel = [GroupModelElement]

只有json中的“name”字段才能进入picker

let group: GroupModelElement
Picker(selection: $session.choiseGroup, label: Text("Выбранная группа")) 
                        ForEach(0 ..< group.name.count) 
                            Text(self.group.name[$0])
                        
                    

与此代码无关的另一个地方完全出现错误。

【问题讨论】:

json 在哪里?你是怎么定义session的? gist.githubusercontent.com/lisindima/… @EnvironmentObject var session: SessionStore 。在这个类中有 Published var choiseGroup = 0 【参考方案1】:

问题在于name 是可选的。您必须打开它才能使其工作。


struct ContentView: View 
    var elements:[GroupModelElement] = [
        GroupModelElement(startYear: 1990, name: "name1", facultyID: "1", specialityID: "2", groupBr: 3, id: "abc1"),
        GroupModelElement(startYear: 1991, name: "name2", facultyID: "10", specialityID: "20", groupBr: 30, id: "abc2"),
        GroupModelElement(startYear: 1992, name: "name3", facultyID: "100", specialityID: "200", groupBr: 300, id: "abc3")
    ]
    @State var selectedIndex = 0

    var body: some View 
        NavigationView 
            Form 
                Section 
                    Picker(selection: $selectedIndex, label: Text("elements")) 
                        ForEach(0 ..< elements.count) 
                            Text(self.elements[$0].name ?? "unknown")
                        
                    
                
            .navigationBarTitle("Select your name")
        
    


我可以建议你在 GroupModelElement 课堂上做些什么。为每个可选变量创建一个计算属性,如下所示:

public struct GroupModelElement: Codable, Hashable 
    public let startYear: Int?
    public var wrappedStartYear:Int
        startYear ?? -1
    
    public let name: String?
    public var wrappedName:String
        name ?? "unknown name"
    
    //...

然后使用可选值会更容易,您可以在选择器内部调用Text(self.elements[$0].wrappedName)

【讨论】:

好的,谢谢,这个选项有效,但我需要使用链接 gist.githubusercontent.com/lisindima/… 将动态数据从 json 添加到选择器

以上是关于从 json 填充选择器,SwiftUI的主要内容,如果未能解决你的问题,请参考以下文章

SwiftUI Picker Help -- 根据另一个选择器的选择填充选择器

SwiftUI Picker 填充问题 - 选择器中的 ForEach 循环不填充

从选择器 SwiftUI 中读取选择

SwiftUI - 使用 CoreData 获取的结果来填充选取器

使用json填充选择器不能按预期工作

SwiftUI 从 CoreData 设置初始选择器值