CollectionView错误[swift]

时间:2016-08-10 03:11:57

标签: swift uicollectionview

有时我会从我的collectionview中得到错误,这是代码:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! SubCategoryDetailsCollectionViewCell

    let grey = UIColor(red: 85.0/255.0, green: 85.0/255.0, blue: 85.0/255.0, alpha: 1.0)
    cell.layer.borderWidth = 1.0
    cell.layer.borderColor = grey.CGColor

    cell.titleLabel.text = name[indexPath.row]
    cell.imageView.sd_setImageWithURL(NSURL(string: thumbImg1[indexPath.row] ))

此行发生错误

    cell.productLabel.text = label[indexPath.row]

    if promo[indexPath.row] == "0"{
        cell.priceLabel.hidden = true
        cell.promoLabel.text = "RM" + price[indexPath.row]
        cell.promoLabel.textColor = UIColor.blackColor()

    }else{
        cell.priceLabel.hidden = false
        cell.promoLabel.text = "RM" + promo[indexPath.row]
        cell.priceLabel.text = "RM" + price[indexPath.row]
        cell.promoLabel.textColor = UIColor.redColor()
        let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: (cell.priceLabel.text)!)
        attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length))
        cell.priceLabel.attributedText = attributeString
    }


    cell.productLabel.text = label[indexPath.row]

    cell.setNeedsDisplay()
    return cell


}

致命错误:索引超出范围

为什么?有时它会工作得很好,但有时候不行。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

indexPath.row的值大于label数组的长度。您可能正在创建超出需要的单元格。检查您在collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int)方法中创建的单元格数。

尝试返回等于标签数组长度的单元格数,这可能会解决您的问题。

override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return label.count
}