Search code examples
swiftuitableviewuipickerview

Insert new row into a section of UITableView based on selected row in UIPickerView - Swift


I have a custom inline UIPickerView (essentially just a expanding/collapsing UIPickerView) and there are 3 options (rows) in the picker view: "Weekly", "Monthly" and "Enter Manually". What I am trying to accomplish is that if a user chooses the row "Enter Manually", a new row is inserted below the row containing the custom UIPickerView (which would contain a custom TextInputCell I have created - but thats aside from the matter). The UITableView represents a form where the user can create an "event" so to speak. There are 4 sections and each section has a different amount of rows, some rows have expanding/collapsing UIPickerViews and others have custom UITextFields, and others have expanding/collapsing UIDatePickers. I only want this to happen for 1 particular UIPickerView, but I cannot seem to get it working. I had tried something like this in the didSelectRowAtIndexPath for when the UIPickerView is collapsed from selecting it's row:

   tableView.beginUpdates()
    if(cell.isKindOfClass(PickerCell)) {
        let pickerTableViewCell = cell as! PickerCell
        if(!pickerTableViewCell.isExpanded() && pickerTableViewCell.rightLabelText() == numClasses[2]) {
            alertOptions.insert("Number of Weeks", atIndex: 1)
            numberOfRowsAtSection[2] = 5
            tableView.insertRowsAtIndexPaths([
                NSIndexPath(forRow: alertOptions.count-3, inSection: 2)
                ], withRowAnimation: .Automatic)
        }
    }
    tableView.endUpdates()

The numClasses is an array with the UIPickerView row data:

let numClasses = ["Weekly", "Monthly", "Enter Manually"]

All the UITableView data is in separate arrays for each section like follows:

var numberOfRowsAtSection: [Int] = [3, 4, 4, 3]

let mainOptions = ["Client Name", "Invoicing Email", "Invoicing Address"]
let dateOptions = ["All Day", "Starts", "Ends", "Time Zone"]
var alertOptions = ["How Many Classes", "Shown on Calendar As", "Alert by Email", "Alert by Text"]
let billingOptions = ["Amount Charged", "Tax Included", "Billing Date"]

And then I suppose I would just put a condition for everything between tableBeginUpdates() and tableEndUpdates() to test if it was the right UIPickerView like:

if(pickerViewTableCell.pickerView == numClassesPicker.pickerView) { ... }

Is what I'm trying to do possible or am I on the right track? Help!

Here are some images for a better visual:

Prior to selecting "Enter Manually":

Before

During selecting "Enter Manually", UIPickerView is expanded:

during

And after, with it now collapsed and "Enter Manually" Selected, What I'm going for here is to now have a new row between "How Many Classes" and "Show on Calendar As":

After


Solution

  • In alertOptions, just add a new object and reload the tableView after you are finished with the action in the pickerView.