Disable drag interaction on specific section

2.9k views Asked by At

How i can disable drag interaction on specific sections or cells if tableView.dragInteractionEnabled = true ?

Now all table cells draggable, but i want to drag specific rows in this table. Is it possible?

3

There are 3 answers

4
xTwisteDx On

Yes, this is possible. First, you need to define which cells are draggable.

In your tableView(cellForRowAt...) method set up a conditional check of some sort.

// Some code to set up your cell
// All cells are disabled by default
// Only enable the one you want to drag.
cell.userInteractionEnabled = false

// Use this conditional to determine which cells
// become dragable.     
if indexPath.row % 2 = 0 {
    // This is the cell you want to be able to drag.
    cell.userInteractionEnabled = true
}

return cell
1
Viktor Gavrilov On

You could do it by returning an empty array in tableView(_:itemsForBeginning:at:)

Return value
An array of UIDragItem objects representing the contents of the specified row. Return an empty array if you do not want the user to drag the specified row.

https://developer.apple.com/documentation/uikit/uitableviewdragdelegate/2897492-tableview

In my case (it's a collection view, but approach is the same) I check type of the cell and allow/forbid dragging depending on it:

func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
    if let cell = collectionView.cellForItem(at: indexPath) as? CalendarCollectionCell {
        let item = cell.calendar!
        let itemProvider = NSItemProvider(object: item.name! as NSString)
        let dragItem = UIDragItem(itemProvider: itemProvider)
        dragItem.localObject = item
        return [dragItem]
    } else {
        return [UIDragItem]()
    }
}
0
ZGski On

You can natively allow/disallow moving cells with the canMoveRowAt method:

func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    return yourDataSource[indexPath.row] is YourMovableCellClass
}