I have a poll system where users are able to create polls. Each poll must have at least two options, with the ability to add up to four.
Right now, I have a collection view cell for each text field, and I load 2 of these cells into the poll's collection view intially.
When a button is clicked, I want to add another one of this collection view cells so it shows another text field.
However, for whatever reason, if I type text into the first and second text fields, and then add two more collection view cells, it adds one text field below the second one and one text field above the first one, when it should simply be appending them all to the bottom.
Here is a visual of what's happening:
+----------------------+
| First text |
+----------------------+
+----------------------+
| Second text |
+----------------------+
Add field button
When I click the add field button twice, this happens:
+----------------------+
| |
+----------------------+
+----------------------+
| First text |
+----------------------+
+----------------------+
| Second text |
+----------------------+
+----------------------+
| |
+----------------------+
And I have no idea why it's doing this and it's driving me insane.
Here is my code (cut out the stuff that's not important):
// Holds the total number of poll options (initially 2, up to 4)
var numPollOptions: Int = 2
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numPollOptions
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NewPollOptionCollectionViewCell", for: indexPath as IndexPath) as? NewPollOptionCollectionViewCell else {
fatalError("The dequeued cell is not an instance of NewPollOptionCollectionViewCell.")
}
cell.presentingViewController = self
cell.initialize(indexPath: indexPath)
return cell
}
@IBAction func onAddPollOptionButtonTapped(_ sender: Any) {
self.numPollOptions += 1
// Allow no more than 4 poll options
if (numPollOptions >= 4) {
addPollOptionButton.isHidden = true
}
self.pollCollectionView.reloadData()
}
What am I doing wrong??
itemForRow?insertItems. Eg: ` self.numPollOptions += 1 pollCollectionView.insertItems(at: [IndexPath(row: numPollOptions - 1, section: .zero)]) `