我目前正在制作一个应用程序,要求用户使用图像选择器将图像加载到CollectionViewCell
。我正在使用一个具有 UIImageView 的原型(prototype)单元格,但是每当我发布照片时,它只会转到第一个单元格,而不是我按下的各个单元格。我想知道如何以针对我点击的特定单元格的方式编写代码并相应地使用图像选择器。
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell
cell.myLabel.text = self.items[indexPath.item]
cell.tag = self.integer[indexPath.item]
cell.backgroundColor = UIColor.yellowColor()
cell.myAdd.addTarget(self, action: "importPicture:", forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
func importPicture(sender: UIButton) {
imagePicker.delegate = self
imagePicker.sourceType = .PhotoLibrary
imagePicker.allowsEditing = true
presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let
cell = myCollection.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)) as! MyCollectionViewCell
var newImage: UIImage
imagePicker.dismissViewControllerAnimated(true, completion: nil)
let pickedImage1 = info[UIImagePickerControllerEditedImage] as? UIImage
currentPickerTarget.image = pickedImage1
currentPickerTarget = cell.myImages
myCollection.reloadData()
}
// MARK: - UICollectionViewDelegate protocol
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// handle tap events
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell
print("You selected cell #\(indexPath.item)!")
print("\(indexPath.row)")
cell.backgroundColor = UIColor.blueColor()
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
// 1
// Return the number of sections
return 1
}
override func viewDidLoad() {
super.viewDidLoad()
let longPressGesture = UILongPressGestureRecognizer(target: self, action: "handleLongGesture:")
self.myCollection.addGestureRecognizer(longPressGesture)
}
最佳答案
发生这种情况是因为您正在重写选取的图像并将其添加到数组的索引 0 中,我将删除行 cell.myAdd.addTarget(self, action: "importPicture:", forControlEvents: UIControlEvents.TouchUpInside)
只需修改函数 func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
}
保存您之前选择的单元格的indexpath.row,然后执行函数 importPicture ,当用户完成选择他的图片时,您将其与您之前保存的索引一起保存到图像数组中,如果您选择相同的单元格图像只会重写自己,新单元格会将新图像添加到数组中。
关于ios - 如何使用 Collection View 单元格的图像选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39290653/