Denis Kartavenko
Denis Kartavenko

Reputation: 81

Disable drag interaction on specific section

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?

Upvotes: 1

Views: 3182

Answers (3)

ZGski
ZGski

Reputation: 2538

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
}

Upvotes: 2

Viktor Gavrilov
Viktor Gavrilov

Reputation: 976

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

Upvotes: 1

xTwisteDx
xTwisteDx

Reputation: 2472

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

Upvotes: 0

Related Questions