Saranya Saranya -4 years ago 105
Swift Question

Custom Collection View cell

I have a collection view with custom cells. I want to populate cells with images by fetching data from two places. One is default image array and another is array which is fetched after parsing

xml web services
. So the final array count is summation of default array count and array count of web services.

How to fetch the images in
cellForItemAt
method of collection view?
can Anyone help me out in this regard?

Answer Source

From above Question

let cell:SubCategoryCollectionViewCell = self.collectionview3.dequeueReusableCell(withReuseIdentifier‌​: "Cell2", for: indexPath) as! SubCategoryCollectionViewCell

if defaultAnimalArray.count-1 >= indexPath.row{ // ex: 0...7 
let item = defaultAnimalArray[indexPath.row]
cell.subThumbImg?.image = UIImage(named: item as! String)
}else{
//If now defaultAnimalArray.count = 8, indexPath = 8 , But array = 0...4, then,
let item = arrayFromAPI[indexPath.row-defaultAnimalArray.count] // 8-8 = 0
cell.subThumbImg?.image = UIImage(named: item as! String)
}
return cell

Alternative 1:-

Declare defaultArray as var.

Before return defautlArray.count+arrayFromAPI.count merge image array also . i.e., defaultArray = defaultArray+arrayFromAPI and return variable becomes return defaultArray.count as well as no changecellForItemAtIndexPath.

Alternative 2:

Declare defaultArray as var and Don't create arrayFromAPI. Just append new images in defaultArray in XML Parsing. After appending a new image reload UICollectionView and also return variable becomes return defaultArray.count

Alternative 3:

With the same code , the item on cellForItemAtIndexPath becomes,

let item = defaultAnimalArray+arrayFromAPI[indexPath.row]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download