JSC
JSC

Reputation: 11

Insert custom UITableViewCell on button click

I've been trying and researching for the whole day and still not able to find the right answer.

I have a button and I want to insert customized UITableViewCell in my static UITableView upon button click.

Here's what I have done. I created an xib file with my customized UITableViewCell and have assigned swift file to it.

In the viewdidload of my tableviewcontroller, I registered my UITableViewCell:

override public func viewDidLoad() {
    super.viewDidLoad()

    let nib = UINib(nibName: "TableViewCell", bundle: nil)
    addContactTableView.registerNib(nib, forCellReuseIdentifier: "cell")
}

Here's my function for my button click:

@IBAction func buttonClick(sender: AnyObject) {        

    if let button = sender as? UIButton {
        if let superview = button.superview {
            if let cell = superview.superview as? UITableViewCell {
                indexPath_g = self.tableView.indexPathForCell(cell)!
            }
        }
    }
    print(indexPath_g.row)
    addContactTableView.beginUpdates()
    addContactTableView.insertRowsAtIndexPaths([
        NSIndexPath(forRow: indexPath_g.row, inSection: 1)
        ], withRowAnimation: .Automatic)
    addContactTableView.endUpdates()
}

And my cellForRowAtIndexPath:

public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath_g) as! TableViewCell

    if(indexPath.section == 1) {
        //Configure the cell...
        cell.detail_field.placeholder = "Phone"

    }
    return cell
}

I tried to run this and I keep getting this error:

fatal error: unexpectedly found nil while unwrapping an Optional value

Upvotes: 1

Views: 529

Answers (2)

orxelm
orxelm

Reputation: 1144

My first guess is your cellForRow method:

public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath_g) as! TableViewCell
 ...
}

change indexPath_g to indexPath

Upvotes: 0

Anirban iOS
Anirban iOS

Reputation: 977

Insert the UITableviewCell in button action. When tapping on button, you can get the indexPath of the cell and insert anywhere in the UItableview.Just add two methods [tableView beginUpdate] and [tableView endUpdate] after inserting the cell using insertRowsAtIndexPaths method.

Upvotes: 0

Related Questions