[英]Insert custom UITableViewCell on button click
I've been trying and researching for the whole day and still not able to find the right answer. 我一直在努力研究,但仍然无法找到正确的答案。
I have a button and I want to insert customized UITableViewCell in my static UITableView upon button click. 我有一个按钮,我想在按钮单击时在我的静态UITableView中插入自定义的UITableViewCell。
Here's what I have done. 这就是我所做的。 I created an xib file with my customized UITableViewCell and have assigned swift file to it. 我用自定义的UITableViewCell创建了一个xib文件,并为其分配了swift文件。
In the viewdidload of my tableviewcontroller, I registered my UITableViewCell: 在我的tableviewcontroller的viewdidload中,我注册了我的UITableViewCell:
override public func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "TableViewCell", bundle: nil)
addContactTableView.registerNib(nib, forCellReuseIdentifier: "cell")
}
Here's my function for my button click: 这是我点击按钮的功能:
@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()
}
And my cellForRowAtIndexPath: 还有我的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
}
I tried to run this and I keep getting this error: 我试图运行这个,我不断收到此错误:
fatal error: unexpectedly found nil while unwrapping an Optional value 致命错误:在展开Optional值时意外发现nil
My first guess is your cellForRow method: 我的第一个猜测是你的cellForRow方法:
public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath_g) as! TableViewCell
...
}
change indexPath_g to indexPath 将indexPath_g更改为indexPath
Insert the UITableviewCell in button action. 在按钮操作中插入UITableviewCell。 When tapping on button, you can get the indexPath of the cell and insert anywhere in the UItableview.Just add two methods [tableView beginUpdate] and [tableView endUpdate] after inserting the cell using insertRowsAtIndexPaths method. 当点击按钮时,您可以获取单元格的indexPath并插入UItableview中的任何位置。在使用insertRowsAtIndexPaths方法插入单元格后,添加两个方法[tableView beginUpdate]和[tableView endUpdate] 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.