1

Example

// My data to use
let items: [Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ...]

/*
  // UICollectionView result I want

  <Section [Item1, Item2, Item3]>
  <Other Section A>
  <Section [Item4, Item5, Item6]>
  <Other Section B>
  <Section [Item7, Item8, Item9]>
  <Other Section A>
  <Section [Item10, Item11, Item12]>
  <Other Section B>
*/

If my data is a Two-Dimensional Array like below, I can see the result easier.

let items: [[Any]] = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ...]

But I think I should use only One-Dimensional Array.

Because my items will add/remove frequently. and need API Communication.. and need LoadMore function.. Maybe these things become complicated if use 2d array. and this problem relate other sections' position.

Is it possible only One-Dimensional Array? and my think is correct?

2
  • How do you decide which item goes in which section? Is it just three items per section? Commented Jun 12, 2017 at 10:02
  • @overactor Yes. Commented Jun 12, 2017 at 11:07

1 Answer 1

1

If you have three items in every section, you can simply calculate how many sections and items per section you'll have:

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return items.count / 3 + 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return min(3, items.count - 3 * section)
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let item = items[indexPath.section * 3 + item]
    // do something with item
}
Sign up to request clarification or add additional context in comments.

2 Comments

Good answer. Thanks!
I knew only about vote.. but it is need 15 reputation. so I thought I couldn't do anything yet. thanks to your comment, I know about 'Mark' now. I won't forget it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.