当我实现以下代码时,不是在节中插入单行,而是插入了两行。
var rowcount = 2
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rowcount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DetailAddIngredientID", for: indexPath) as! DetailAddIngredientTableViewCell
cell.addMoreButton.tag = indexPath.section
cell.addMoreButton.addTarget(self, action: #selector(addMoreField(_:)), for: .allTouchEvents)
return cell
}
@objc func addMoreField(_ sender : UIButton){
rowcount = rowcount + 1
detailTable.beginUpdates()
detailTable.insertRows(at: [(NSIndexPath(row: rowcount - 1, section: 1) as IndexPath)], with: .automatic)
detailTable.endUpdates()
}
如何才能在节中只插入一行?
问题就出在这一行。
cell.addMoreButton.addTarget(self, action: #selector(addMoreField(_:)), for: .allTouchEvents)
你使用了 .allTouchEvents
对于 UIControl.Event
这将导致你的函数在每次点击按钮时被多次调用。
将其改为 .touchUpInside
将解决这个问题,当用户触摸按钮后,只响应一次,然后将手指移开。 这是按钮的默认事件。