我对数据数组有问题,在此数据数组中,我发送了6张图像的名称,以便稍后将它们加载到CollectionView中,这6张图像加载得很好,没有任何问题,但是当我添加String时值发送给我,这是一个空的错误:
这是我的课程,我的数据数组在哪里:
import UIKit
class HBook{
var imagenB: UIImage!
var estatus: String!
init(estatus: String, imagenB: UIImage) {
self.estatus = estatus
self.imagenB = imagenB
}
class func getData() -> [HBook]{
let rawData = [
["imagenB":"book1"],
["imagenB":"book2"],
["imagenB":"book3"],
["imagenB":"book4"],
["imagenB":"book5"],
["imagenB":"book6"],
["estatus":"No reservado"]
]
var hbook:[HBook] = []
for item in rawData{
hbook.append(HBook(estatus: item["estatus"]!, imagenB: UIImage(named: item["imagenB"]!)!))
}
return hbook
}
}
我打印数据数组以查看哪个变量为空,但显然所有变量都有一个赋值:
我不知道为什么要发送一个空值。
此信息是在另一个具有CollectionView和Label的类中检索的,我传递信息的方法在cellForItemAt方法中:
class DetailViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var contenedorCollection: UIView!
@IBOutlet weak var myCollection: UICollectionView!
@IBOutlet weak var pages: UIPageControl!
@IBOutlet weak var estatus: UILabel!
var hbook = HBook.getData()
var nombreH = ""
override func viewDidLoad() {
super.viewDidLoad()
pages.numberOfPages = hbook.count
self.title = nombreH
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return hbook.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CellCollectionViewCell
cell.imageview.image = hbook[indexPath.row].imagenB
estatus.text = hbook[indexPath.row].estatus
return cell
}
答案 0 :(得分:1)
我认为问题出在数据类中。请用下面的代码替换您的HBook类,它将在不作任何进一步更改的情况下起作用:
class HBook{
var imagenB: UIImage?
var estatus: String?
init(estatus: String? = nil, imagenB: UIImage? = nil) {
self.estatus = estatus
self.imagenB = imagenB
}
class func getData() -> [HBook]{
let rawData = [
["imagenB":"book1","estatus":"No reservado"],
["imagenB":"book2","estatus":"No reservado"],
["imagenB":"book3","estatus":"No reservado"],
["imagenB":"book4","estatus":"No reservado"],
["imagenB":"book5","estatus":"No reservado"],
["imagenB":"book6","estatus":"No reservado"]
]
var hbook:[HBook] = []
for item in rawData{
if let image = item["itemnB"]{
hbook.append(HBook(estatus: item["estatus"], imagenB:UIImage(named:image)))
}else{
hbook.append(HBook(estatus: item["estatus"]))
}
}
return hbook
}
}