我创建了一个从图像数组中提取的集合视图(现在只有8个,但用户可以添加更多)。我最初使用的是一个scrollview,但是通过一个集合发现它更容易,并且由于这个伟大的社区,我去了一个集合视图。我需要找到indexPath来删除给定点的项目。所以这是我到目前为止的一些代码,但我具体是新手。这是我目前的一些代码。
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var myCollectionView: UICollectionView!
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! UserFeedCollectionViewCell
cell.myImage.image = UIImage(named: imageArray[indexPath.row])
cell.myImage.layer.cornerRadius = 12.0
cell.myImage.clipsToBounds = true
return cell
}
//delete item at current item - 2
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.row > 2 {
myCollectionView.deleteItems(at: [])
}
}
希望这会有所帮助,如果您有疑问,请随时在评论中提问。
编辑:启用了分页,它是水平滚动,每个图像占用整个单元格。
答案 0 :(得分:0)
如何保持图像索引的数组?
为顶部的索引定义变量:
var selected = [IndexPath]()
然后将didSelectItemAt
实现为:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selected.append(indexPath)
if selected.count > 2 {
let ndx = selecte.count - 3
let twoBack = selected[ndx]
myCollectionView.deleteItems(at:[twoBack])
}
}
以上内容适用于第一次选择,但在此时,您需要弄清楚如何处理下一个选择 - 是否擦除selected
数组并重新开始,或需要跟踪进一步选择以处理下一个输入。
根据您的处理方式,需要删除selected
数组或修改该数组以删除已删除的项目。