Adding new Item to CollectionView programmatically, via the last Item

时间:2017-08-04 12:16:05

标签: ios swift uicollectionview

I'm facing an issue with CollectionView, I want to see a collection of images and have an add button as the last item so first of all I've made an array of NSData as I'm gonna save those images to Core Data var photoArray = [NSData]() then I implement UICollectionViewDataSource

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

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if indexPath.item == photoArray.count + 1 {
        present(imagePicker, animated: true, completion: nil)
    }
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return photoArray.count + 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "photoItem", for: indexPath) as? PhotoCell else {return UICollectionViewCell()}
    cell.btn.tag = indexPath.item

    if indexPath.item == photoArray.count + 1 {
        cell.thumImage.image = UIImage(named: "add_button")
        cell.btn.isHidden = true
        print("first")
        return cell
    } else {
        let img = photoArray[indexPath.item]
        cell.configureAddingImage(img: img)
        print("second")
        return cell

    }
}

Actually I'm facing with the problem in "cellForItemAt indexPath" like "fatal error: index is out of range" I tried to make array look like var photoArray: [NSData]! but it caused other problems, please give me any advice or help, thank you!

1 个答案:

答案 0 :(得分:0)

Index is out of range because items or rows are indexed from 0

Should be like this:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "photoItem", for: indexPath) as? PhotoCell else {return UICollectionViewCell()}
        cell.btn.tag = indexPath.row

        if indexPath.row == photoArray.count {
            cell.thumImage.image = UIImage(named: "add_button")
            cell.btn.isHidden = true
            print("first")
            return cell
        } else {
            let img = photoArray[indexPath.row]
            cell.configureAddingImage(img: img)
            print("second")
            return cell

        }
    }
相关问题