【问题标题】:List to display data from server in swiftUI列表以在 swiftUI 中显示来自服务器的数据
【发布时间】:2021-11-06 02:28:13
【问题描述】:

我正在从服务器获取数据,我需要像在此站点中显示的那样显示它 SwiftUI - nested list

来自服务器的数据是

  "OptionsListByItemId": [
        {
         "Choices": [
           {
             "ChoiceId": 1284226,
              "ChoiceName": "Hot",
            },
            { 
              "ChoiceId": 1284227,
              "ChoiceName": "Cool",
            }
          ],
          "OptionId": 187472,
          "OptionName": "Temperature"
      },
    
      { 
       "Choices": [
           {
             "ChoiceId": 1284223,
              "ChoiceName": "61%",
            },
            { 
              "ChoiceId": 1284224,
              "ChoiceName": "70%",
            }
          ],
          "OptionId": 187473,
          "OptionName": "Humidity"
 ]
}

我的模型是这样的

struct OptionsandChoices : Decodable , Identifiable{
    
    var id: String{OptionName}
    var OptionName: String!
    var OptionId: Int
    var Choices : [ChoiseList]
    
}

struct OptionsandChoiceList: Decodable{
    
    var OptionsListByItemId:[OptionsandChoices]  
}
struct ChoiseList: Decodable {
    var ChoiceName: String!
    var ChoiceId: Int
}

ViewModel 是

class ItemChoiceViewModel : ObservableObject{
 @Published var OpnChoice: OptionsandChoiceList = OptionsandChoiceList(OptionsListByItemId: [])
 // fetching data from server 
}

我的 swiftUI 视图喜欢

struct ItemView: View {
 var OpnChoice = OptionsandChoiceList(OptionsListByItemId: [])
 @ObservedObject var choicevwModel = ChoiceViewModel()

struct Optionspage: View {
   var body: some View {
   List(choicevwModel.OpnChoice.OptionsListByItemId) {opn in 
       Text(opn.OptionName)
   }
}

我无法在列表中使用 ChoiceName

我怎样才能在 OptionName 下面的每一行中获得choiceName,就像我给出的链接中一样

列表应该显示为

 Temperature 
    Hot 
    Cold 
 
 Humidity
    61%
    70%

目前我排成两排

 Temperature
 Humidity

【问题讨论】:

标签: ios iphone xcode ipad swiftui


【解决方案1】:

您正在寻找的物业位于Choices。要获得它的价值,请编写以下内容:

opn.Choices[yourIndex].OptionName

另外,如果你想使用@ObservedObject,请使用OptionsandChoiceList 类而不是struct 并使其符合ObservableObject 协议。最后,在此处声明@Published 属性。

final class OptionsandChoiceList: ObservableObject, Decodable {
    @Published var OptionsListByItemId: OptionsandChoices = []  
}

【讨论】:

  • 名字的选择太糟糕了,连代码编写者都搞不清楚是怎么回事。
  • 我完全同意,命名很糟糕。
  • 如果我给出 Text(opn.Choices.ChoiceName) 它会给我错误“'[ChoiseList]' 类型的值没有成员 'ChoiceName'”
  • @RomaKavinskyi 我写的就像你说的那样,它给了我一个错误。虽然 ChoiceList 有 ChoiceName 它显示错误
  • 目前进展如何?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-13
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 2019-11-01
  • 1970-01-01
相关资源
最近更新 更多