There is a problem with your approach if the number of rows in the table exceeds the number that can fit on the screen. In this case, cells that scroll outside the screen will be reused, and the contents of the nameInput text box will be lost. If you can be sure that this will never happen, use the following code (in a method that processes short buttons) to compose your array:
var arrayOfNames : [String] = [String]() for var i = 0; i<self.arrayOfPeople.count; i++ { let indexPath = NSIndexPath(forRow:i, inSection:0) let cell : EditingCell? = self.tableView.cellForRowAtIndexPath(indexPath) as EditingCell? if let item = cell?.nameInput.text { arrayOfNames.append(item) } } println("\(arrayOfNames)")
As an alternative....
However, if it is possible that the cells will scroll behind the scenes, I propose another solution. Set a delegate for the nameInput text fields, and then use the delegate methods to grab the names as you type them.
First, add variables to the view controller to hold the array and line number of the text field being edited.
var arrayOfNames : [String] = [String]() var rowBeingEdited : Int? = nil
Then in your cellForRowAtIndexPath method add:
cell.nameInput.text = ""
Then add two new functions to catch when text fields start / end:
func textFieldDidEndEditing(textField: UITextField) { let row = textField.tag if row >= arrayOfNames.count { for var addRow = arrayOfNames.count; addRow <= row; addRow++ { arrayOfNames.append("")
When the user clicks the button, they can still edit one of the names. To satisfy this, add the following to a method that processes button taps:
if let row = rowBeingEdited { let indexPath = NSIndexPath(forRow:row, inSection:0) let cell : EditingTableViewCell? = self.tableView.cellForRowAtIndexPath(indexPath) as EditingTableViewCell? cell?.nameTextField.resignFirstResponder() }
This forces textField to complete editing and, therefore, invokes the didEndEditing method, thereby saving the text in an array.
pbasdf
source share