Reputation: 529
I have an array of a custom class that is used to populate a UICollectionView.
Additional arrays of the same custom class are created as they are received from other iOS devices (via Multipeer Connectivity). Data objects are contained within the class type, and so are quite large which I do not want to make copies of and my current logic, I was thinking of retaining them in separate arrays.
With this in mind, how do I manage the UICollectionView delegate methods?
Item count suggestion. Presuming the 2nd array is empty until MPC sends it's data, its count would be 0 :
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return array1.count + array2.count
}
How do I control the indexPath in cellForItemAt between 2 arrays?
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CustomCell
if indexPath.item < array1.count {
cell.labelTitle.text = array1[indexPath.item].title
} else {
// IS THIS RIGHT, AS CALCULATED INDEXPATH?
if array2 != nil {
cell.labelTitle.text = array2[indexPath.item - array1.count].title
}
}
return cell
}
Or is this completely the wrong approach? This seems harder to manage...
Upvotes: 0
Views: 183
Reputation: 119380
You can use a helper computed property:
var totalArray: [OriginalContentType] { return array1 + array2 }
then treat it like normal.
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return totalArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CustomCell
cell.labelTitle.text = totalArray[indexPath.item].title
}
Upvotes: 1