简体   繁体   English

从CollectionView单元格复制时出错(快速)

[英]Error when copy from CollectionView cell (Swift)

I make Drag and Drop app. 我制作拖放应用程序。

He is work fine, but copy from cell not work. 他工作很好,但是从牢房复制不起作用。

When i tap on collection view cell, i have error. 当我点击集合视图单元格时,我出错了。

My code for copy: 我的复制代码:

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

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

Error - Thread 1: signal SIGABRT 错误-线程1:信号SIGABRT

2018-04-02 19:54:35.520913+0500 DragBook[6891:189120] [MC] Reading 2018-04-02 19:54:35.520913 + 0500 DragBook [6891:189120] [MC]阅读
from private effective user settings. 来自私人有效用户设置。 Could not cast value of type 无法转换类型的值
'DragBook.ImageCollectionViewCell' (0x10e67e0e0) to 'DragBook.ImageCollectionViewCell'(0x10e67e0e0)至
'DragBook.TextCollectionViewCell' (0x10e67e4e0). 'DragBook.TextCollectionViewCell'(0x10e67e4e0)。 2018-04-02 2018年4月2日
19:54:48.631190+0500 DragBook[6891:189120] Could not cast value of 19:54:48.631190 + 0500 DragBook [6891:189120]无法强制转换为
type 'DragBook.ImageCollectionViewCell' (0x10e67e0e0) to 键入'DragBook.ImageCollectionViewCell'(0x10e67e0e0)来
'DragBook.TextCollectionViewCell' (0x10e67e4e0). 'DragBook.TextCollectionViewCell'(0x10e67e4e0)。 (lldb) (LLDB)

Solution: 解:

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")
}

The problem is that the cell may be imageCell and you force cast it as textCell 问题在于该单元格可能是imageCell,并且您强制将其强制转换为textCell

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

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM