Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change background of a cell that's being drag with iOS11+ drag-n-drop?

I'm trying to implement the new drag-n-drop methods in UICollectionView and can't figure out how to remove the background from a cell that's being dragged.

Here's a screenshot of the problem:

enter image description here

Here's the code I'm trying:

func collectionView(_ collectionView: UICollectionView, dragPreviewParametersForItemAt indexPath: IndexPath) -> UIDragPreviewParameters? {
    let parameters = UIDragPreviewParameters()
    parameters.backgroundColor = .clear
    return parameters
}

Problem is, it doesn't really work. The background is still visible. I'm thinking of using visiblePath: UIBezierPath, but I don't think it's going to play nice with text.

Is there a way to just remove this background completely?

like image 785
Senõr Ganso Avatar asked Sep 25 '18 17:09

Senõr Ganso


2 Answers

I'm not sure there is a way to do so without using UIBezierPath.

Here is an example of what I did for something similar:

final class CustomCell: UITableViewCell {
    @IBOutlet weak var mySuperLabel: UILabel!
    @IBOutlet weak var whiteSubview: UIView! // I have added a cornerRadius of 12.0 in the XIB
}

enter image description here

Then, the delegate method:

func tableView(_ tableView: UITableView, dragPreviewParametersForRowAt indexPath: IndexPath) -> UIDragPreviewParameters? {
    let cell = tableView.cellForRow(at: indexPath) as! CustomCell
    let previewParameters = UIDragPreviewParameters()
    let path = UIBezierPath(roundedRect: cell.whiteSubview.frame, cornerRadius: 12.0)
    previewParameters.visiblePath = path
    previewParameters.backgroundColor = .clear
    return previewParameters
}

And the result:

enter image description here

like image 82
Rob Avatar answered Nov 20 '22 13:11

Rob


Another way to do this is to use ItemProvider when a drag will begin.

func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
    let itemProvider = NSItemProvider()
    let dragItem = UIDragItem(itemProvider: itemProvider)
    dragItem.previewProvider = { () -> UIDragPreview? in
        let cell = collectionView.cellForItem(at: indexPath) // Do cell preview modifications here
        cell?.layer.backgroundColor = UIColor.clear.cgColor
        cell?.backgroundColor = .clear
        return UIDragPreview(view: cell!)
    }
    return [dragItem]
}
like image 1
rohanphadte Avatar answered Nov 20 '22 15:11

rohanphadte