In iOS, how can I detect if a cell in UITableview is in the process of being swiped?
Asked Answered
B

2

5

I'm using leadingSwipeActionsConfigurationForRowAt to detect and process swipes. However, I need to be able to detect when the user started to swipe, but before it completes. The problem is that if I update the table using reloadData() or beginUpdates() / endUpdates() while a cell is being swiped, it resets the cell to the un-swiped position (and I don't like that kind of user experience). I want to be able to delay the cell/data update until the swipe is finished or cancelled.

Butyrin answered 2/3, 2021 at 5:53 Comment(2)
You could implement willTransition(to:) in the UITableViewCell to detect a swipe: developer.apple.com/documentation/uikit/uitableviewcell/…Jackdaw
That will work. I'll need to keep track of the state of any cell that transitions out of the default state, but it'll definitely let me do what I need. Can you please post it as an answer so that I can mark it as being correct?Butyrin
B
9

Even though Andreas' answer is absolutely correct, I found an easier way to do it. Apparently, whenever leadingSwipeActionsConfigurationForRowAt is used, the cell is marked as being edited whenever it starts being swiped. And that allows us to use willBeginEditingRowAt and didEndEditingRowAt on the UITableView, without having to worry about the UITableViewCell

var swipedRow: IndexPath? = nil
        
func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {
    swipedRow = indexPath
}
    
func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) {
    swipedRow = nil
}

And then you can just check if swipedRow == nil (plus, if it's not nil, you will know the indexPath of the row being swiped)

Butyrin answered 3/3, 2021 at 14:45 Comment(0)
J
1

You could implement willTransition(to:) in the UITableViewCell` to detect a swipe, see: UITableViewCell documentation

There, just set a flag in the view controller to prevent updates. You might also need to do something in viewWillDisappear or so, because maybe the transition callbacks are not called under some circumstances.

Jackdaw answered 2/3, 2021 at 14:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.