Parth Bhuva
Parth Bhuva

Reputation: 877

UITextField values inside UICollectionView cell in swift

I have UITextField and an ImageView inside UICollectionView cell. It loads data from web service. The user can input data inside the text field and have to submit it. My problem is, when I scroll the collection view, the entered value in one text field in a cell got messed up with other text field values from another cell, and it displays wrong values.

my steps(suppose I have cells A, B, ......., k)

1.entering values

Cell A Textfield= 12
Cell B Textfield= 13

2.scrolling down

(I haven't entered anything in cell F Textfield, though it shows 13)

3.scrolling back to where I entered values

Cell A Textfield= 12
Cell B Textfield= (blank)

Upvotes: 2

Views: 2671

Answers (3)

Shinigami
Shinigami

Reputation: 2213

UICollectionView and UITableView reuse a handful of cell objects as you scroll. This helps with memory management. It also means that when you populate one text field on a cell, that text field's cell will get reused for a different row as you scroll, so if you don't reset the text field's content, you'll see the same data showing up for the wrong rows.

The solution is that your "source of truth" (aka model) must always be separate from your UI. So when the user types something in a text field, your model (perhaps an array of strings?) should be updated accordingly. Then when the user scrolls, you must use tableView:cellForRowAtIndexPath: or collectionView:cellForItemAtIndexPath: methods to populate the cell with the appropriate data. If there is no data, you must clear any data that may have been left over from another row whose cell got reused.

Other opportunities you'll have to deal with cell reuse include the willDisplayCellForRowAtIndexPath method on UITableViewDelegate, or prepareForReuse on UITableViewCell. Collection view objects have corresponding methods as well.

Upvotes: 2

Suryakant Sharma
Suryakant Sharma

Reputation: 3960

As far as I can understand from question I think the problem is, you are not updating values every time - cellForRowAtIndexPath function gets called on scrolling.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

what you need to do to resolve this issue is "You have to store all the values you have entered in your cell's textField and whenever above datasource method gets called for UITableView, updated cell accordingly".

Upvotes: 0

Bhanu
Bhanu

Reputation: 1249

You can solve this problem by keeping the values of UITextField in an Array. Whenever you are entering value to UITextField and dismissing keyboard,then save that value to array at the same cell index value in array and when you scroll your collectionView, the textfield value should entered from array and it won't misplace value.

Upvotes: 2

Related Questions