JSON仅在所有单元格Swift 4中显示最后一个可选

Posted

技术标签:

【中文标题】JSON仅在所有单元格Swift 4中显示最后一个可选【英文标题】:JSON only showing last optional in all cells Swift 4 【发布时间】:2017-09-25 23:05:20 【问题描述】:

所以下面贴出的代码就是我的stuct

 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")

它现在显示文本,但当我有三个单元格时,它只显示最后一个名为 Monster 的可选选项,而不显示所有其他选项。它只在每个单元格中显示怪物。 应该是

第一格:Cowboy-bebpop 第二单元:牛仔-bebop-tengoku-no-tobira 第三格:三角枪 等等

表格查看方法:

     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))
    


细胞功能:

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.
    



【问题讨论】:

您的nameLabel 在tableView 或CollectionView 中在哪里? 如果它在一个 diff 类中我如何访问它,我知道全局变量,但我不太确定它是如何工作的。 您的设计似乎有缺陷。您在单元格中调用jsonDecoding。这不是必需的。您可以在 ViewDidLoad 中调用它并将数据保存到数组中。您可以在集合视图cellForItemAt 中将数据设置为集合单元格。 请查看***.com/questions/46425131/… 【参考方案1】:

如果你的 jsonDecoding() 函数被放置在每个单元格中,它将获取所有项目,然后在 for 循环里面,它将循环访问每个获取的项目,将标签从第一个更改为最后一个。一旦达到最后一个标签将永远不会再改变。

【讨论】:

以上是关于JSON仅在所有单元格Swift 4中显示最后一个可选的主要内容,如果未能解决你的问题,请参考以下文章

Swift如何仅在我的数据库中有值时才显示表格视图单元格

多细胞类型swift 4.2

使用 SWIFT 3 的单元格不显示没有 html 标记的更新 JSON

Swift 数组不返回所有值

限制tableView中显示的单元格数量,滚动到最后一个单元格时加载更多单元格

JSON 结果在 Swift 中的 Tableview 中显示结果列表,而不是每个单元格中的每个结果(附图片)[关闭]