Ios 单击按钮时插入自定义UITableViewCell

Ios 单击按钮时插入自定义UITableViewCell,ios,swift,uitableview,static,Ios,Swift,Uitableview,Static,我一整天都在努力研究,仍然没有找到正确的答案 我有一个按钮,我想在我的静态UITableView中插入自定义的UITableViewCell 以下是我所做的。我用自定义的UITableViewCell创建了一个xib文件,并为其分配了swift文件 在tableviewcontroller的viewdidload中,我注册了UITableViewCell: override public func viewDidLoad() { super.viewDidLoad() let

我一整天都在努力研究,仍然没有找到正确的答案

我有一个按钮,我想在我的静态UITableView中插入自定义的UITableViewCell

以下是我所做的。我用自定义的UITableViewCell创建了一个xib文件,并为其分配了swift文件

在tableviewcontroller的viewdidload中,我注册了UITableViewCell:

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

    let nib = UINib(nibName: "TableViewCell", bundle: nil)
    addContactTableView.registerNib(nib, forCellReuseIdentifier: "cell")
}
这是我的按钮点击功能:

@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()
}
和我的手机号码:

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
}
我尝试运行此操作,但一直出现以下错误:

致命错误:在展开可选值时意外发现nil


我的第一个猜测是你的cellForRow方法:

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

indexPath\u g更改为indexPath

我的第一个猜测是您的cellForRow方法:

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

将indexPath更改为indexPath,在按钮操作中插入UITableviewCell。点击按钮时,您可以获取单元格的indexPath并插入UItableview中的任意位置。只需在插入单元格后使用InsertRowstIndeXPaths方法添加两个方法[tableView beginUpdate]和[tableView endUpdate]。

在按钮操作中插入UItableview单元格。点击按钮时,您可以获取单元格的indexPath并插入UItableview中的任意位置。只需在插入单元格后使用InsertRowstIndeXPaths方法添加两个方法[tableView beginUpdate]和[tableView endUpdate]