【问题标题】:How to change background of a cell that's being drag with iOS11+ drag-n-drop?如何通过 iOS11+ 拖放更改正在拖动的单元格的背景?
【发布时间】:2018-09-25 17:53:06
【问题描述】:

我正在尝试在 UICollectionView 中实现新的拖放方法,但不知道如何从被拖动的单元格中删除背景。

这是问题的截图:

这是我正在尝试的代码:

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

问题是,它并没有真正起作用。背景仍然可见。我正在考虑使用visiblePath: UIBezierPath,但我认为它不会很好地处理文本。

有没有办法完全删除这个背景?

【问题讨论】:

  • 好像没有人尝试过使用新的拖放功能。没有一个关于它的问题得到解答,所有教程都只关注最基本的东西。

标签: ios swift uicollectionview


【解决方案1】:

我不确定是否有不使用UIBezierPath 的方法来做到这一点。

这是我为类似的事情所做的一个例子:

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
}

然后,委托方法:

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
}

结果:

【讨论】:

  • 是的,似乎没有办法做到这一点。我最终回到了旧的 D&D 风格,没有新的 API。
  • 非常适合我。我还用dropPreviewParametersForRowAt 实现了相同的代码
【解决方案2】:

另一种方法是在拖动开始时使用 ItemProvider。

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

【讨论】:

  • 在我的情况下不起作用,但我想我的手机有点定制,所以也许它会对其他人有用。看起来很有希望
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-04
  • 1970-01-01
相关资源
最近更新 更多