簡體   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