CollectionView is blank



我试图在collectionview上显示问题,其中每个单元格都有questionLabel,但我无法在collectionViewCell上看到问题,这只是一个空白屏幕。我想知道在下面的实现中我缺少了什么。

读取数据

class ReadData {

static let shared = ReadData()
let questionsData: String

private init() {
self.questionsData = """
{
"questions" :[
{
"text" : "What is your name?",
"type" : "string"
},
{
"text" : "What is your age?",
"type" : "integer"
}
]
}
"""
}
}

问题集合ViewCell

import UIKit
final class QuestionCollectionViewCell: UICollectionViewCell {

@IBOutlet weak var questionLbl: UILabel!
@IBOutlet weak var answerTF: UITextField!

@IBAction func nextButtonTapped(_ sender: Any) {
print("Hi")
}
}

问题ViewController

import UIKit
class QuestionsViewController: UIViewController {
@IBOutlet weak var questionCollectionView: UICollectionView!

var decodedData = [Questions]()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupCollectionView() 
let readData = ReadData.shared.questionsData
let jsonData = Data(readData.utf8)
let decodedData = try? JSONDecoder().decode(Questions.self, from: jsonData)
// I could see the data in the terminal
print(decodedData)
questionCollectionView.reloadData()
}

func setupCollectionView() {
questionCollectionView.delegate = self
questionCollectionView.dataSource = self
}

}
extension QuestionsViewController: UICollectionViewDelegate {


}
extension QuestionsViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "QuestionsCollectionViewCell", for: indexPath) as? QuestionCollectionViewCell
else {
return UICollectionViewCell()

}
// the break point hits here and collectionview cell type is QuestionCollectionViewCell
cell.questionLbl.text = "Hi"
return cell
}
}

问题。swift

import Foundation
struct Questions:Codable {
let questions: [Question]
}
// MARK: - Question
struct Question:Codable {
let text, type: String
}

试着像这样为集合视图单元格设置一个非零大小。

extension QuestionsViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 60, height: 60)
}
}

最新更新