CollectionView Error [swift]



有时我会从我的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

}

致命错误:索引超出范围

为什么?有时它会工作得很好,但有时不是。有人能帮忙吗?

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

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

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

最新更新