2017-09-25 36 views
0

所有細胞,使貼在下面的代碼是我stuctJSON只顯示最後一個可選斯威夫特4

struct AnimeJsonStuff: Decodable { 
    let data: [AnimeDataArray] 
} 

struct AnimeLinks: Codable { 
    var selfStr : String? 

    private enum CodingKeys : String, CodingKey { 
     case selfStr  = "self" 
    } 
} 
struct AnimeAttributes: Codable { 
    var createdAt : String? 
    var slug : String? 
    private enum CodingKeys : String, CodingKey { 
     case createdAt  = "createdAt" 
     case slug = "slug" 
    } 
} 
struct AnimeRelationships: Codable { 
    var links : AnimeRelationshipsLinks? 

    private enum CodingKeys : String, CodingKey { 
     case links  = "links" 
    } 
} 

struct AnimeRelationshipsLinks: Codable { 
    var selfStr : String? 
    var related : String? 

    private enum CodingKeys : String, CodingKey { 
     case selfStr  = "self" 
     case related  = "related" 
    } 
} 

struct AnimeDataArray: Codable { 
    let id: String? 
    let type: String? 
    let links: AnimeLinks? 
    let attributes: AnimeAttributes? 
    let relationships: [String: AnimeRelationships]? 

    private enum CodingKeys: String, CodingKey { 
     case id = "id" 
     case type = "type" 
     case links = "links" 
     case attributes = "attributes" 
     case relationships = "relationships" 
    } 
} 

此代碼是我的分析數據功能:

func jsonDecoding() { 

    let jsonUrlString = "https://kitsu.io/api/edge/anime" 

    guard let url = URL(string: jsonUrlString) else {return} 
    URLSession.shared.dataTask(with: url) { (data, response, err) in 
     guard let data = data else {return} 
     do { 
      let animeJsonStuff = try JSONDecoder().decode(AnimeJsonStuff.self, from: data) 
      for anime in animeJsonStuff.data { 
       // print(anime.id) 
       // print(anime.type) 
       // print(anime.links?.selfStr) 
       let animeName = anime.attributes?.slug 
       print(animeName) 
       DispatchQueue.main.async { 
        self.nameLabel.text = animeName 
       } 

       for (key, value) in anime.relationships! { 
        // print(key) 
        // print(value.links?.selfStr) 
        // print(value.links?.related) 
       } 
      } 
     } catch let jsonErr { 
      print("Error serializing json", jsonErr) 
     } 
     }.resume() 
} 

這是控制檯打印出:

Optional("cowboy-bebop") 
Optional("cowboy-bebop-tengoku-no-tobira") 
Optional("trigun") 
Optional("witch-hunter-robin") 
Optional("beet-the-vandel-buster") 
Optional("eyeshield-21") 
Optional("honey-and-clover") 
Optional("hungry-heart-wild-striker") 
Optional("initial-d-fourth-stage") 
Optional("monster") 
Optional("cowboy-bebop") 
Optional("cowboy-bebop-tengoku-no-tobira") 
Optional("trigun") 
Optional("witch-hunter-robin") 
Optional("beet-the-vandel-buster") 
Optional("eyeshield-21") 
Optional("honey-and-clover") 
Optional("hungry-heart-wild-striker") 
Optional("initial-d-fourth-stage") 
Optional("monster") 
Optional("cowboy-bebop") 
Optional("cowboy-bebop-tengoku-no-tobira") 
Optional("trigun") 
Optional("witch-hunter-robin") 
Optional("beet-the-vandel-buster") 
Optional("eyeshield-21") 
Optional("honey-and-clover") 
Optional("hungry-heart-wild-striker") 
Optional("initial-d-fourth-stage") 
Optional("monster") 

現在顯示的文本,但它只顯示最後一個可選叫做怪物,而不是所有的O當我有三個細胞的時候。它只在每個單元格中顯示怪物。 它應該是

第一細胞:牛仔-bebpop 第二細胞:牛仔波普-天國-NO-TOBIRA 第三細胞:槍神Trigun 和等

表視圖方法:

 let nameLabel: UILabel = { 
     let label = UILabel() 
     label.textColor = UIColor.black 

     return label 
    }() 
    let profileImageView: UIImageView = { 
     let imageView = UIImageView() 
     imageView.contentMode = .scaleAspectFit 
     return imageView 
    }() 

    let synopsis: UILabel = { 
     let label = UILabel() 
     label.textColor = UIColor.black 

     return label 
    }() 


    override init(frame: CGRect) { 
     super.init(frame: frame) 
     setupViews() 
     jsonDecoding() 
     self.layer.shadowOpacity = 0.05 
     self.layer.shadowRadius = 0.05 
     self.layer.cornerRadius = 1 



    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 

    func setupViews() { 
     backgroundColor = UIColor(red:0.86, green:0.87, blue:0.89, alpha:1.0) 
     addSubview(nameLabel.self) 
      addSubview(synopsis.self) 
     addConstraintsWithFormat("H:|-18-[v0]|", views: synopsis) 
     addConstraintsWithFormat("V:|-8-[v0]|", views: synopsis) 
     addConstraintsWithFormat("H:|-12-[v0]|", views: nameLabel) 
    } 
} 

extension UIColor { 

    static func rgb(_ red: CGFloat, green: CGFloat, blue: CGFloat) -> UIColor { 
     return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: 1) 
    } 

} 

extension UIView { 

    func addConstraintsWithFormat(_ format: String, views: UIView...) { 
     var viewsDictionary = [String: UIView]() 
     for (index, view) in views.enumerated() { 
      let key = "v\(index)" 
      viewsDictionary[key] = view 
      view.translatesAutoresizingMaskIntoConstraints = false 
     } 

     addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary)) 
    } 

} 

Cell函數:

override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 

     navigationItem.title = "Kitsu - Your anime feed" 

     collectionView?.backgroundColor = UIColor(red:0.09, green:0.13, blue:0.19, alpha:1.0) 
     collectionView?.register(viewControllerCells.self, forCellWithReuseIdentifier: cellId) 
    } 


     override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
     return 3 
    } 

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
     return collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) 
    } 

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 
     return CGSize(width: 350, height: 150) 
    } 

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { 
     return UIEdgeInsets(top: 15, left: 0, bottom: 10, right: 0) 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


} 
+0

你的'nameLabel'在tableView或CollectionView中? –

+0

我如何訪問,如果它在差異類我知道全局變量,但我不太確定這將如何工作。 – Dengekiko

+0

看起來你的設計存在缺陷。你在cell中調用jsonDecoding。這不是必需的。你可以在ViewDidLoad中調用它並將數據保存到數組中。您可以在集合視圖'cellForItemAt'中將數據設置爲集合單元格。 –

回答

0

如果你的jsonDecoding()函數被放置在每個單元格中,它會將fet ch所有項目,然後在for循環內部,它將循環訪問每個從第一個到最後一個標籤更改標籤。一旦到達最後,標籤將不再改變。