Passing an image when taped on uicollectionview to a detail view controller in swift

北慕城南 提交于 2019-12-23 03:51:56

问题


Ive been at this for a while but cant seem to crack it in swift

I want a user to be able to select an image in uicollectionView and for that image to appear in a detailed view controller, i can do this quite easily with a peice of text, and i can do this when there is a static array of images preloaded. but i cant seem to get anywhere with a collectionview which is loaded with images from a camera.

I understand i need to use

override func performSegueWithIdentifier(identifier: String, sender: AnyObject?) {
  }

and this function to isolated selected cell.

  func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
  }

I do have these outlets @IBOutlet weak var collectionView: UICollectionView!

  var images = [UIImage]()

image picker stores all images to this array by

  images.insert(newImage, atIndex: 0)

when the array would be passed to the detailviewcontroller, i understand that would have to be copied into another local array and then how would i get the current image that was highlighted to be shown first, perhaps using indexPath.Row

Regards


回答1:


I'm not using segues, and actually I don't quite understand what your problem is, but I'll try to show you how it could be achieved.

First of all, you have an array with images, so I believe your image should be accessed as images[indexPath.row]

let's suppose that you already have UIViewController class with UIImageView in it. if so, you can write something like that:

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    let myVC = MyViewController()
    myVC.imageView.image = images[indexPath.row]
    self.presentViewController(myVC, animated: true, completion: nil)
}

for modal or

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    let myVC = MyViewController()
    myVC.imageView.image = images[indexPath.row]
    self.navigationController?.pushViewController(myVC, animated: true)
}

if you want to show it as navigational.

I believe that with segues it's basically the same but I think you have to use func prepareForSegue for, you know, preparing the segue (func performSegueWithIdentifier will just perform it). In prepareForSegue you should check identifier of your segue

if segue.identifier == "myIdentifier" {
  //your code here
}

and if this identifier is right, put your commands to your myVC there.



来源:https://stackoverflow.com/questions/32914463/passing-an-image-when-taped-on-uicollectionview-to-a-detail-view-controller-in-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!