Search code examples
iosobjective-cswiftuitableviewuipickerview

insert inline date pickerView cell - swift


I'm trying to implement inline date picker view using this class , here is the code as shown in the example on this class :

 var cells:NSMutableArray = []
let datePickerCell = DatePickerCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)

  //in ViewDidLoad : 

   cells = [datePickerCell]


    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    // Get the correct height if the cell is a DatePickerCell.
    let cell = self.tableView(tableView, cellForRowAtIndexPath: indexPath)
    if let datePickerCell = cell as? DatePickerCell {
        return datePickerCell.datePickerHeight()
    }

    return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    // Deselect automatically if the cell is a DatePickerCell.
    let cell = self.tableView(tableView, cellForRowAtIndexPath: indexPath)
    if let datePickerCell = cell as? DatePickerCell {
        datePickerCell.selectedInTableView(tableView)
        self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }


}

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

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return cells.count
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    return cells[indexPath.row] as! UITableViewCell
}

I wanted to insert rows when click on button , using this code :

 func insert() {
    cells.addObject(datePickerCell)


    let insertionIndexPath = NSIndexPath(forRow: cells.count - 1, inSection: 0)

    tableView.insertRowsAtIndexPaths([insertionIndexPath], withRowAnimation: .Automatic)
}

what I get is empty cells with no date picker view , I also tried to add another datePickerCell to cells array :

cells = [datePickerCell , datePickerCell]

the same thing happens , nothing but empty cell

image showing the empty cells and only one date picker view

any help ?


Solution

  • Just replace your function of button with

    func insert() {
            let datePickerCell = DatePickerCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
            cells.addObject(datePickerCell)
                   self.tableView.beginUpdates()
            self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: cells.count-1, inSection: 0)], withRowAnimation: .Bottom)
            self.tableView.endUpdates()
    }