我有這樣如何在swift中解析Json文件進行2次集合視圖?
{
"dicts": [
{
"main": "",
"note1": "",
"note2": "",
"note3": "",
"note4": ""
},
{
"main": "",
"note1": "",
"note2": "",
"note3": "",
"note4": "",
"note5": ""
},
{
"main": "",
"note1": "",
"note2": ""
}
]
}
我的應用JSON文件2 view controllers
各有collection view
。在第一個collection view
我將顯示JSON數據main
爲每個cell
,當我點擊main
我有困難設置note
數據爲各自main
內容在每個cell
。所有我能夠打電話給任何一個note
價值。
型號:
struct SecPage {
var note1:String?
var note1:String?
var note2:String?
var note3:String?
var note4:String?
var note5:String?
}
static func downSec() -> [SecPage] {
let jsonFile = Bundle.main.url(forResource: "info", withExtension: "json")
let jsonData = try? Data(contentsOf: jsonFile!)
var noteArray = [SecPage]()
do{
if let jsonResult = try JSONSerialization.jsonObject(with: jsonData!, options: .mutableContainers) as? Dictionary<String,AnyObject>{
let name = jsonResult["dicts"] as? [Dictionary<String,AnyObject>]
for note in name!{
let note1 = note["note1"] as? String
let note2 = note["note2"] as? String
let note3 = note["note3"] as? String
let note4 = note["note4"] as? String
let note5 = note["note5"] as? String
let noteinfo = SecPage(note1: note1 ,note2: note2,note3: note3, note4: note4, note5: note5, note6: note6)
noteArray.append(noteinfo) }} } catch{print("note not found")}
return noteArray
}
查看
class CollectionViewCell2: UICollectionViewCell {
@IBOutlet weak var img: UIImageView!
@IBOutlet weak var names: UILabel!
func updateUIsec(data:dataObj) {
names.text = data.note1
}
}
如何在細胞更新的時候,我可以能夠在name.text
只輸入一個數據,以及如何有效地使用Model class
檢索json
文件併發送到view
。
你可以改變你的JSON?這不是非常有用。而不是使用'note1'' note2'等,你應該有'notes'這是一個字符串數組。 – Paulw11
那麼如果我有'筆記'數組,如何更新'單元格標籤'? – Digs
那麼,你會有一個'SecPage'結構,它具有'main''String'屬性和''notes'' [String]'屬性。將您的JSON解析爲這些結構的數組。然後,將適當的元素從數組傳遞給第二個視圖控制器。 – Paulw11