Varsha Vinod
Varsha Vinod

Reputation: 289

Swift 5 UITableViewCell : Multiple row insertion instead of single row

When I implemented the following code, instead of inserting a single row in the section, two rows are being inserted.

    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()
    }

How can I insert only a single row in the section?

Upvotes: 1

Views: 460

Answers (1)

rbaldwin
rbaldwin

Reputation: 4848

The issue is caused on this line:

cell.addMoreButton.addTarget(self, action: #selector(addMoreField(_:)), for: .allTouchEvents)

You are using .allTouchEvents for the UIControl.Event which will cause your function to be called multiple times every time the button is tapped.

Changing that to .touchUpInside will fix the issue by only responding once, when the user touches the button and then lifts their finger off. This is the default event used for buttons.

Upvotes: 1

Related Questions