Passing data between View Controllers (Swift)

扶醉桌前 提交于 2019-12-14 03:57:40

问题


I'm trying to pass an Image from one view to another and my code doesn't seem to be working- it takes the user to the new view but the image isn't transferred over as well. Any help would be greatly appreciated!

So, here's a button called Post that takes the user to a new view.

@IBAction func postButton(sender: AnyObject) {

    performSegueWithIdentifier("toBrowsePage", sender: nil)


}

Then, in another file for the other view controller...

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "toBrowsePage" {


    var itemToAdd = segue.destinationViewController as! ListPage

    itemToAdd.postingImage.image = browsingImage.image

    }

}

回答1:


Never assign image directly from another ViewController like this:

itemToAdd.postingImage.image = browsingImage.image

But instead of doing that just pass the imageName to the next View Controller and create one instance into your nextViewController which holds this image name and after that you can assign that image with in ViewDidLoad method of other ViewController.

consider this example:

you can pass ImageName this way:

itemToAdd.imageName = "YourImageName"

In your nextViewController create an instance which hold this String:

var imageName = ""

In your ViewDidLoad method:

postingImage.image = UIImage(named: imageName)

Hope this will help.




回答2:


Its because you are trying to set the image of UIImageView which is not there in memory so it will not be displayed.

Instead you need to pass only image object to next controller. Create on properly for your Image in next controller & then pass the image from this controller to next controller.




回答3:


In your ListPage ViewController define an UIImage

var newImage: UIImage?

Now In prepareForSegue:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

if segue.identifier == "toBrowsePage" {

      var itemToAdd = segue.destinationViewController as! ListPage
      itemToAdd.newImage = browsingImage.image
      }
    }

Now in ListPage ViewDidLoad method set Image:

postingImage.image = newImage


来源:https://stackoverflow.com/questions/31554620/passing-data-between-view-controllers-swift

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