我希望删除数组而不是将其发送到另一个UIViewController

问题描述

我正在尝试创建一个功能,该功能允许用户选择多个视频,然后选择一个按钮,它将选择的视频发送到另一个阵列。我已经有一个处理删除的类似功能。我真的只是想重新利用我已有的删除代码,但是我尝试过的一切都失败了。我是Swift新手,但是有办法做到这一点还是我应该采取的更好的方法?

var videos = [PHAsset]()
var dictionarySelectedIndexPath: [IndexPath: Bool] = [:]

@objc func didDeleteButtonClicked(_ sender: UIBarButtonItem) {
    var deleteNeededIndexPaths: [IndexPath] = []
    for (key,value) in dictionarySelectedIndexPath {
        if value {
            deleteNeededIndexPaths.append(key)
        }
    }
    for i in deleteNeededIndexPaths.sorted(by: { $0.item > $1.item }) {
        videos.remove(at: i.item)
    }
    collectionView.deleteItems(at: deleteNeededIndexPaths)
    dictionarySelectedIndexPath.removeAll()
}

func getVideos() {
    let assets = PHAsset.fetchAssets(with: PHAssetMediaType.video,options: nil)
    assets.enumerateObjects({ (object,count,stop) in
        self.videos.append(object)
    })
    
    self.videos.reverse()
    self.collectionView.reloadData()
    collectionView.delegate = self
    collectionView.dataSource = self
    let nib = UINib(nibName: "ItemCollectionViewCell",bundle: nil)
    collectionView.register(nib,forCellWithReuseIdentifier: cellIdentifier)
}

override func prepare(for segue: UIStoryboardSegue,sender: Any?) {
    if segue.identifier == "videoEditorSegueIdentifier" {
        let otherVc = segue.destination as! VideoEditorVC
        otherVc.videos = videos
    }
}


func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier,for: indexPath) as! ItemCollectionViewCell            
        let asset = videos[indexPath.row]
        let manager = PHImageManager.default()

        if cell.tag != 0 {manager.cancelImageRequest(PHImageRequestID(cell.tag))}
        
        cell.tag = Int(manager.requestImage(for: asset,targetSize: CGSize(width: 120.0,height: 120.0),contentMode: .aspectFill,options: nil) { (result,_) in cell.imageView?.image = result
        })
        
        return cell
    }

解决方法

据我所知,您遇到的问题是因为您将indexPath存储在字典中以记住选择的内容,并且难以将其转换为您持有的实际数据

如果您切掉中间人并在didSelectItemAt方法中用实际选择的对象简单地填充数组,这会容易得多。

以下内容:

var selectedVideos = [PHAsset]()

func videoFor(indexPath: IndexPath) -> PHAsset {
    // return the video more or less the same as you do it in cellForItemAt:
}

func indexFor(video: PHAsset) -> Int? {
    return selectedVideos.firstIndex(of: video)
}

func collectionView(_ collectionView: UICollectionView,didSelectItemAt indexPath: IndexPath) {
    let video = videoFor(indexPath: IndexPath)
    if selectedVideos.contains(video) {
        selectedVideos.remove(at: index)
    } else {
        selectedVideos.append(video)
    }
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...