问题描述
我正在尝试创建一个功能,该功能允许用户选择多个视频,然后选择一个按钮,它将选择的视频发送到另一个阵列。我已经有一个处理删除的类似功能。我真的只是想重新利用我已有的删除代码,但是我尝试过的一切都失败了。我是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)
}
}