2016-05-30 55 views
1

我一直在嘗試和研究整整一天,仍然無法找到正確的答案。在按鈕單擊插入自定義UITableViewCell

我有一個按鈕,我想在按鈕點擊時在我的靜態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

回答

0

我的第一個猜測是你的cellForRow方法:

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

變化indexPath_g到indexPath

0

插入的UITableViewCell的按鈕操作。當按鈕攻,你可以得到電池的indexPath並插入在UItableview.Just任意位置添加兩種方法將使用insertRowsAtIndexPaths方法細胞後[的tableView的BeginUpdate][的tableView endUpdate]

相關問題