簡體   English   中英

如何將圖像從CollectionView傳輸/顯示到另一個ViewController

[英]How to transfer/display an image from CollectionView to another ViewController

我查了很多例子並嘗試合並,但都沒有成功。 在我的CollectionView(已放置在ViewController中)中,我想選擇一個單元格並將單元格圖像推送到另一個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
}

附加類:CollectionViewCell類

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

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

附加類:UIViewController

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

    var story: StoryImages?

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

}

附加類: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類型的對象,您StoryView在其中傳遞圖像並在viewDidLoad使用該對象來分配圖像

var selectedStory: StoryImages?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM