ios - 从 CollectionView 单元格复制时出错(Swift)

标签 ios swift drag-and-drop copy uicollectionviewcell

我制作了拖放应用。

他工作正常,但从单元格复制不工作。

当我点击 Collection View 单元格时,出现错误。

我的复制代码:

let cell = collectionView.cellForItem(at: indexPath) as! TextCollectionViewCell
UIPasteboard.general.string = cell.textLabel?.text

cellForItemAt

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let item = everitems[indexPath.row]

    switch item {
    case .text(let content):
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TextCollectionViewCell", for: indexPath) as! TextCollectionViewCell
        cell.configureWithText(content)
        cell.layer.cornerRadius = 8.0
        cell.layer.masksToBounds = true
        return cell
    case .image(let content):
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCollectionViewCell", for: indexPath) as! ImageCollectionViewCell
        cell.layer.cornerRadius = 8.0
        cell.layer.masksToBounds = true
        cell.configureWithImage(content)
        return cell
    }
}

错误 - 线程 1:SIGABRT 信号

2018-04-02 19:54:35.520913+0500 DragBook[6891:189120] [MC] Reading
from private effective user settings. Could not cast value of type
'DragBook.ImageCollectionViewCell' (0x10e67e0e0) to
'DragBook.TextCollectionViewCell' (0x10e67e4e0). 2018-04-02
19:54:48.631190+0500 DragBook[6891:189120] Could not cast value of
type 'DragBook.ImageCollectionViewCell' (0x10e67e0e0) to
'DragBook.TextCollectionViewCell' (0x10e67e4e0). (lldb)

解决方案:

if let cell = collectionView.cellForItem(at: indexPath) as? ImageCollectionViewCell{
      UIPasteboard.general.image = cell.imageView?.image
      print("Image")
} else if let cell = collectionView.cellForItem(at: indexPath) as? TextCollectionViewCell{
      UIPasteboard.general.string = cell.textLabel?.text
      print("Text")
}

最佳答案

问题是单元格可能是 imageCell 而你强行将它转换为 textCell

if let cell = collectionView.cellForItem(at: indexPath) as? TextCollectionViewCell{

}
else
{
    /// it's image cell
    let cell = collectionView.cellForItem(at: indexPath) as! ImageCollectionViewCell

}

关于ios - 从 CollectionView 单元格复制时出错(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49613645/

相关文章:

ios - ios相机对焦不佳

ios - View 和 super View 之间的自动布局标准空间不起作用

iOS SDK Hue Philips with Swift

c++ - 如何在 *.exe 上启用拖动文件并将其作为参数获取?

java - 有条件的拖放图像

iOS8 核心数据 "use of unimplemented initializer"

ios - 压缩或压缩 iOS sqlite 数据库

ios - pod Facebook分享问题

ios - 访问相机和照片库

html - 聚合物.dart : drag and drop of elements inside ShadowDom