如何 transfer/display 从 CollectionView 到另一个图像 ViewController

How to transfer/display an image from CollectionView to another ViewController

我查阅了很多例子并尝试合并但没有成功。在我的 CollectionView(已放置在 ViewController 中)中,我想 select 一个单元格并将单元格图像推送到另一个 ViewController。图像已放置在字典数组中。我不确定,我应该如何编辑我的 prepareForSegue 或我的 func collectionView...didSelectItemAtIndexPath。此外,任何与您的代码一起使用的详细解释都会有所帮助,因为我仍在学习 swift 及其语法。

以下是我认为您需要的所有信息,但如果您需要更多信息,请告诉我:

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

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "ShowToStory") {
        var story = sender as! UICollectionViewCell, indexPath = collectionView.indexPathForCell(story)

    }
}

private func initStoryImages() {

    var storyArchives = [StoryImages]()
    let inputFile = NSBundle.mainBundle().pathForResource("StoryArchive", ofType: "plist")

    let inputDataArray = NSArray(contentsOfFile: inputFile!)

    for inputItem in inputDataArray as! [Dictionary<String, String>] {

        let storyImage = StoryImages(dataDictionary: inputItem)
        storyArchives.append(storyImage)       
}
      storyImages = storyArchives
}

其他 CLASS:CollectionViewCell class

class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var cellImage: UIImageView!

func setStoryImage(item:StoryImages){
cellImage.image = UIImage(named:item.itemImage)
}
}

其他 CLASS:UIViewController

class StoryView: UIViewController{
@IBOutlet weak var ImageToStory: UIImageView!

    var story: StoryImages?

override func viewDidLoad() {
    super.viewDidLoad()
    ImageToStory.image = UIImage(named: (story?.itemImage)!)
}

}

其他 CLASS:StoryImages

class StoryImages{

var itemImage: String


init(dataDictionary:Dictionary <String,String>) {
itemImage = dataDictionary["ItemImage"]!
}

class func newStoryImage(dataDictionary:Dictionary<String,String>) -> StoryImages {
return StoryImages(dataDictionary: dataDictionary)
   }
 }
}

首先在didSelectItemAtIndexPath

中传递selectedItem的indexPath

现在像这样在prepareForSegue方法中传递图像

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "ShowToStory") {
        let cell = sender as! UICollectionViewCell //Change UICollectionViewCell with CustomCell name if you are using CustomCell
        let indexPath = self.collectionView?.indexPathForCell(cell) 
        let story = storyImages[indexPath.row]
        let destVC = segue.destinationViewController as! StoryView
        destVC.selectedStory = story
    }
}  

现在在您要传递图像的 StoryView 中声明一种 StoryImages 类型的对象,并在 viewDidLoad 中使用该对象来分配图像

var selectedStory: StoryImages?

override func viewDidLoad() {
    super.viewDidLoad()
    ImageToStory.image = selectedStory.itemImage // or use NSData if it contain url string
}