繁体   English   中英

单击按钮时插入自定义UITableViewCell

[英]Insert custom UITableViewCell on button click

我一直在努力研究,但仍然无法找到正确的答案。

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

我试图运行这个,我不断收到此错误:

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

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

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

indexPath_g更改为indexPath

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM