ios - 在单击按钮时插入自定义 UITableViewCell

标签 ios swift uitableview static

我一整天都在尝试和研究,但仍然找不到正确的答案。

我有一个按钮,我想在单击按钮时在我的静态 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()
}

还有我的 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
}

我试着运行它,但我一直收到这个错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

最佳答案

在按钮操作中插入 UITableviewCell。点击按钮时,您可以获得单元格的索引路径并插入 UItableview 中的任何位置。只需在插入后添加 [tableView beginUpdate][tableView endUpdate] 两个方法使用 insertRowsAtIndexPaths 方法的单元格。

关于ios - 在单击按钮时插入自定义 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37520117/

相关文章:

ios - 如何在 Realm 中移动对象

JavaScript:input.focus() 并显示 Cursor

ios - 如何使用 PHAssetResourceRequestOptions progressHandler/PHAssetResourceProgressHandler

ios - NSUserDefaults 在设备和模拟器上工作,但在通过 .ipa 安装时在设备上返回 NULL

ios - 在具有委托(delegate)的 View Controller 之间传递多个值

swift - 是否可以缩短对更高级别功能的评估?

ios - 位于 cellAtIndexPath 中的查询

ios - 预期返回“UITableViewCell”的函数中缺少返回值

ios - 了解可选链接和可选解包选项

ios - "' isSuccess ' is inaccessible due to ' 内部 ' protection level",AlamoFire 不像以前那样工作