简体   繁体   English

Swift - 从 UIColllectionViewCell 获取 UIImage

[英]Swift - get UIImage from UIColllectionViewCell

I have a collectionView where each cell contains a UIImage and an empty UIButton .我有一个collectionView ,其中每个cell都包含一个UIImage和一个空的UIButton How do I the picture that the user tapped on?我如何查看用户点击的图片?

class ImageCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout{

    @IBOutlet weak var imageCollectionView: UICollectionView!

    let images: [UIImage] = [
        UIImage(named: "beerImage")!,
        UIImage(named: "christmasImage")!,
        UIImage(named: "goalImage")!,
        UIImage(named: "travelImage")!,
        UIImage(named: "rollerImage")!,
        UIImage(named: "giftImage")!,
        UIImage(named: "shirtImage")!,
        UIImage(named: "dressImage")!,

    ]

    let columnLayout = FlowLayout(
        itemSize: CGSize(width: 150, height: 150),
        minimumInteritemSpacing: 30,
        minimumLineSpacing: 10,
        sectionInset: UIEdgeInsets(top: 20, left: 20, bottom: 10, right: 20)
    )

    var colViewWidth: CGFloat = 0.0

    override func viewDidLoad() {

        self.imageCollectionView.collectionViewLayout = columnLayout

        super.viewDidLoad()

        imageCollectionView.dataSource = self
        imageCollectionView.delegate = self
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! ImageCollectionViewCell

        cell.imageView.image = images[indexPath.item]
        cell.layer.cornerRadius = 2
        return cell
    }

    @IBAction func imageButtonTapped(_ sender: Any) {
        print("tapped")
    }


    @IBAction func closeButtonTapped(_ sender: Any) {
        let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let HomeViewController = storyBoard.instantiateViewController(withIdentifier: "HomeVC") as! ExampleViewController
                self.present(HomeViewController, animated: false, completion: nil)
    }
}

Update更新

In the end I would like to pass that image to another ViewController.最后,我想将该图像传递给另一个 ViewController。 I tried it this way but the picture isn't showing up in the other ViewController:我尝试过这种方式,但图片没有显示在另一个 ViewController 中:

ViewControllerA视图控制器A

var tappedImage = UIImage()
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    tappedImage = images[indexPath.row]
}

var showPopUpView = true

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    print(showPopUpView)
    var vc = segue.destination as! ExampleViewController
    vc.pickedImage = self.tappedImage
    vc.ShowPopUpView = self.showPopUpView

}

ViewControllerB视图控制器B

    var pickedImage = UIImage()

override func viewDidLoad() {
        super.viewDidLoad()

        imagePreview.image = pickedImage

You could do something like this你可以做这样的事情

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    imageToPass = images[indexPath.row]
}

Edit: As far as passing that image to your next view controller, one possible way is to add a property to your first and second view controllers for the image, set that image in your didSelectItemAt call, then pass it using prepare(for segue: UIStoryboardSegue, sender: Any?)编辑:至于将该图像传递给您的下一个视图 controller,一种可能的方法是将属性添加到图像的第一个和第二个视图控制器,在您的didSelectItemAt调用中设置该图像,然后使用prepare(for segue: UIStoryboardSegue, sender: Any?)

let imageToPass: UIImage?

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if segue.identifier == "identifier name here" {

       // Get the new view controller using segue.destination.
       if let destVC = segue.destination as? SecondViewController {
           // Pass the selected object to the new view controller.
           destVC.image = imageToPass
       }
   }
}

Duo to the conversation in comments:评论中的对话二重奏:

The order of actions should be:动作的顺序应该是:

  1. User clicks on a cell用户单击单元格
  2. Fetching the image according to the indexPath of the selected cell根据所选单元格的indexPath获取图像
  3. Setting it in a temporary variable ( tappedImage )将其设置为临时变量( tappedImage
  4. Performing segue执行转场
  5. Pass the temporary image to the destination's temporary image ( pickedImage )将临时图像传递给目的地的临时图像( pickedImage
  6. Loading the destination's view加载目的地的视图
  7. Show the image.显示图像。

Seems like you are missing one of these steps ( probably the step 3, since you are not calling performSegue in the ...didSelectItemAt indexPath... and it maybe not getting called at all! Try print something there and check if it's true )好像你错过了这些步骤之一(可能是第 3 步,因为你没有在 ...didSelectItemAt indexPath 中调用performSegue ...didSelectItemAt indexPath...而且它可能根本没有被调用!尝试在那里打印一些东西并检查它是否是真的)

Or you may disorder the flow ( probably you setting the image after destination's View is loaded and the result is to not seeing that. )或者您可能会打乱流程(可能您在目标View加载设置图像,结果是看不到。)

Debug:调试:

Try printing all variables you have access (eg tappedImage , pickedImage , images[indexPath.row] , etc.) on each these 7 states and see where is the issue and where are you loosing the selected image reference尝试在这 7 个状态中打印您可以访问的所有变量(例如tappedImagepickedImageimages[indexPath.row]等),看看问题出在哪里以及您在哪里丢失了选定的图像参考

Possible issue可能的问题

You are not using ...didSelectItemAt indexPath... to performSegue , Probably you have a UIButton for that, so the button is blocking the cell from getting selected.您没有使用...didSelectItemAt indexPath... performSegue执行Segue ,可能您有一个UIButton ,因此该按钮阻止了cell被选中。

Try this尝试这个

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let image = images[indexPath.row]
    //Result image
}

(or) If you want to get image from button tap (Not recommended) (或)如果您想通过按钮点击获取图像(不推荐)

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
   let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! ImageCollectionViewCell

   cell.imageView.image = images[indexPath.item]
   cell.layer.cornerRadius = 2

   //Replace your button
   cell.yourButton.tag = indexPath.row
   cell.yourButton.addTarget(self, action: #selector(self.imageButtonTapped(_:)), for: .touchUpInside)
}

in button action在按钮动作中

func imageButtonTapped(_ sender: UIButton) {
   let image = images[sender.tag]
   //Result image
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM