0
votes

I am a beginner in Swift and i am stuck with a problem.

I have a TableView Controller which contains 3 sections, the first two are composed of one textfield in one cell. However, for the third one at the beginning, it has only one cell (textfield). Each time the user presses Return on the textfield, i would like to insert one row composed of one textfield below the textfield edited. (Like when you add multiple phone numbers in the Contacts App).

I created a UITextField Array : TextFieldArrayPayers

My code looks like this : Connected to the textField when user presses Return :

@IBAction func AddParticipant(sender: AnyObject) {
        tableView.beginUpdates()
        textFieldArrayPayers.append(UITextField());
        tableView.insertRowsAtIndexPaths([
            NSIndexPath(forRow: textFieldArrayPayers.count, inSection: 2)
            ], withRowAnimation: .Automatic)
        tableView.endUpdates()

    }

And to manage my sections :

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 3
    }

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section==2
    {
        return textFieldArrayPayers.count+1
    }
    else
    {
        return 1;
    }
}

When I run my program, i try to edit the first textfield and when I press Enter or Return, I get this :

Terminating app due to uncaught exception 'NSRangeException',
reason: '*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'

I looked at numerous similar topics but never found the real solution..

Thanks in advance for those who got the solution

1
What is the code for cellForRowAtIndexPath? - beyowulf
Empty, I do not know how to implement it.. - AntoineP

1 Answers

0
votes

Update your model before beginning your batch update:

@IBAction func AddParticipant(sender: AnyObject) {

        textFieldArrayPayers.append(UITextField());

        tableView.beginUpdates()
        tableView.insertRowsAtIndexPaths([
            NSIndexPath(forRow: textFieldArrayPayers.count, inSection: 2)
            ], withRowAnimation: .Automatic)
        tableView.endUpdates()

    }

For more information on see the Table View Programming Guide for iOS