【问题标题】:UITableView sections from JSON data swift来自 JSON 数据的 UITableView 部分 swift
【发布时间】:2016-09-21 09:37:19
【问题描述】:

我有这样的 JSON 数据:

[{"name":"Rice","Menu":{"title":"titl1"}},{"name":"Name2","Menu":{"title":"title2"}}]

我想为每对 [id, name] 构建一个包含一个部分的表格视图。部分标题应该是菜单标题,每个部分的唯一单元格应该是名称值。

如何将 JSON 数据解析为数组并使用 array.count 确定必须显示多少部分?

编辑

class Menus {
   private var _name:String!
   private var _title:String!

   var name:String {
      return _name
   }

   var title:String {
      return _title
   }

   init(nam:String, title:String) {
      _name = nam
      _title = title
   }
}

新编辑

x.forEach {
   if let uw = ($0["name"]).string {
      um.insert(uw)
      if let hru = ($0["Menu"]["title"]).string {
         us.insert(hru)
      }
   }
}

for i in um {
   for u in us {
      var men = Menus(nam: i, tit: u)
      self.menus.append(men)
   }
}

【问题讨论】:

    标签: ios json swift uitableview


    【解决方案1】:
    var arrData:[[String:AnyObject]]! = [
        ["name":"Rice",
            "Menu":
                [
                    "title":"titl1"
            ]
        ],
        [
            "name":"Name2",
            "Menu":
                [
                    "title":"title2"
            ]
        ]
    ]
    
    var arrMenu:[Menus]! = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        for i in 0..<arrData.count {
            let dish = arrData[i]
            let menu = dish["Menu"] as! [String:String]
    
            let name = dish["name"] as! String
            let title = menu["title"]
    
            arrMenu.append(Menus.init(nam: name, title: title!))
        }
    
    
    }
    // MARK: - Table view data source
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return arrMenu.count
    }
    
    override func tableView( tableView :UITableView, titleForHeaderInSection section: Int)->String{
        let menu:Menus = arrMenu[section]
        return menu.name
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
    
        let menu = arrMenu[indexPath.section]
    
        cell.textLabel?.text = menu.title
    
        return cell
    }
    

    【讨论】:

    • 谢谢,我会试试的
    • 我想用一个型号Menu可以用吗?
    • var menus = [Menus]()
    • 非常感谢,我会检查一下
    • 如何将json数据保存到arrData
    猜你喜欢
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多