如何将图像选择器用于集合视图单元格

时间:2016-09-02 10:53:09

标签: ios swift view collections cells

我目前正在制作一个应用程序,要求用户使用图像选择器将图像加载到CollectionViewCell。我正在使用一个具有UIImageView的原型单元格,但每当我发布一张照片时,它只会进入第一个单元格而不是我按下的单个单元格。我想知道如何以一种针对我所点击的特定单元格的方式制作代码并相应地使用图像选择器。

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

1 个答案:

答案 0 :(得分:0)

这是因为您正在重写拾取的图像并将其添加到数组的索引0,我将删除行cell.myAdd.addTarget(self, action: "importPicture:", forControlEvents: UIControlEvents.TouchUpInside)并只修改函数func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { }以保存indexpath.row你提前选择的单元格,然后执行函数importPicture,当用户完成选择他的图片时,你将它保存到你之前保存的索引的图像数组中,如果选择相同的单元格,图像将重写自己和新的单元格会将新图像添加到数组中。