0

I have a UitableView with 3 section (3 cell), In section 1 I have a list of item where user can delete using button, all delete process is good but when I delete a item; the uitableview goes to top and goes to bottom (is something like reload the view) and I want that

When user delete a item only remove from position this is my code

    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var value: Int = 0
        if(section == 0){
            value = 1
        }else if(section == 1){
            value = items.count //20
        }else if(section == 2){
            value = 1
        }
        return value
    }

    @objc func delete_item(sender: UIButton){
        let point = sender.convert(CGPoint.zero, to: tv_items)
        guard let indexPath = tv_items.indexPathForRow(at: point) else{
            return
        }
        tv_items.beginUpdates()
        self.items.remove(at: indexPath.row)
        tv_items.deleteRows(at: [indexPath], with: .fade)
        tv_items.endUpdates()
    }


    cell.btn_delete.tag = indexPath.row
    cell.btn_delete.addTarget(self, action: #selector(delete_item), for: .touchUpInside)

Thanks in advance

Israel
  • 121
  • 10

2 Answers2

0

If you are using estimatedHeightForRowAt, disable this and use heightForRowAt function.

Alternatively, use this after endUpdates():

tv_items.scrollToRow(at: indexPath, at: .top, animated: false)

If you have a constant row height, you can use:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 80 // or any constant height
}

If you need varying height based on content, lemme know what the content is so I can help.

elliott-io
  • 1,394
  • 6
  • 9
0

Use the below method and I think it will solve your issue:-

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
return 50.0 // height of the row (Eg. 50.0)
}

a.palo
  • 258
  • 2
  • 12