iosswiftuitableviewuilongpressgesturerecogni

how show user selected cell of tableview on longpress


Hello i am adding UILongPressGesture in my tableview and i have added successfully but issue is that how to show that cell is selected i mean i want change color of selected cell and when i again do longpress on selected cell than i want to delselect cell

i have try to add long press in my tableview with code and assign delegates on LongPress here is my code

 @objc func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {

        if longPressGestureRecognizer.state == UIGestureRecognizer.State.began {

            let touchPoint = longPressGestureRecognizer.location(in: self.tblList)
            if let indexPath = tblList.indexPathForRow(at: touchPoint) {


            }
        }
    }

And in viewDidload() i am writing this code

let longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(SMSChatViewController.longPress(_:)))
        longPressGesture.minimumPressDuration = 1.0 // 1 second press
        longPressGesture.delegate = self
        self.tblList.addGestureRecognizer(longPressGesture)

so from this code i am able to select cell but how to show user that the cell is selected i don't know how to do this

so i just want like that when user is do longpress than cell color change and set as selected and then again do longpress than deselect cell with its original color


Solution

  • What about you change just the backgroundColor of the cell, when the longPressGesture is recognized? Something like this:

    @objc func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {
    
            if longPressGestureRecognizer.state == UIGestureRecognizer.State.began {
    
                let touchPoint = longPressGestureRecognizer.location(in: self.tblList)
                if let indexPath = tblList.indexPathForRow(at: touchPoint) {
                    let cell = tblList.cellForRow(at: indexPath)
                    if (cell.isSelected) {
                        cell.backgroundColor = UIColor.clear // or whatever color you need as default
                        cell.setSelected(false, animated: true)
                    } else {
                        cell.backgroundColor = UIColor.orange
                        cell.setSelected(true, animated: true)
                    }
    
                }
            }
        }
    

    If you need clarification or i missunderstood a thing let me know and i will edit my answer.