在集合视图中执行numberof节时崩溃

时间:2018-12-18 12:19:27

标签: ios swift collections

您好,我正在填充UICollectionView,但是当执行节数时,它会给我错误

错误

  

解开值时发现nil

这是我的代码

var subjects: SubjectResponse?


    func callSubChapAPI(){
        let preferences = UserDefaults.standard
        let studentlvl = "student_lvl"
        let student_lvl = preferences.object(forKey: studentlvl) as! String
        print(student_lvl)
        let params = ["level_id": student_lvl]
        Alamofire.request(subListWithChapter, method: .post, parameters: params).responseData() { (response) in
            switch response.result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    decoder.keyDecodingStrategy = .convertFromSnakeCase

                     self.subjects = try decoder.decode(SubjectResponse.self, from: data)

                    self.collView.reloadData()
                } catch {
                    print(error.localizedDescription)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
}

extension ExploreTableViewCell : UICollectionViewDataSource {

   func numberOfSections(in collectionView: UICollectionView) -> Int {
            return self.subjects!.subjectList.count
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.subjects!.subjectList.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ExploreCollectionViewCell
        let url = subjects!.subjectList[indexPath.section].subList[indexPath.row].chImage
        print(url)
        return cell
    } 
}

但是我要崩溃了,所以请帮助我为什么我做错了地方就崩溃了

1 个答案:

答案 0 :(得分:3)

numberOfSections中,您需要返回subjectList中的主题数,如果subjectsnil,则返回0

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return subjects?.subjectList.count ?? 0
}

现在subjectList中的每个主题都具有数组subList的属性。在numberOfItemsInSection中返回subList中某些subjectList元素的数量(现在您可以强制展开subjects,因为您知道如果numberOfSections更大然后是0)

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return subjects!.subjectList[section].subList.count
}