Swift 5 UITableViewCell:多行插入而不是单行
Swift 5 UITableViewCell : Multiple row insertion instead of single row
当我实现以下代码时,没有在该部分中插入一行,而是插入了两行。
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)
您正在为 UIControl.Event
使用 .allTouchEvents
,这将导致每次点击按钮时多次调用您的函数。
将其更改为 .touchUpInside
将通过仅在用户触摸按钮然后松开手指时响应一次来解决此问题。这是用于按钮的默认事件。
当我实现以下代码时,没有在该部分中插入一行,而是插入了两行。
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)
您正在为 UIControl.Event
使用 .allTouchEvents
,这将导致每次点击按钮时多次调用您的函数。
将其更改为 .touchUpInside
将通过仅在用户触摸按钮然后松开手指时响应一次来解决此问题。这是用于按钮的默认事件。