1

I have tried 2 methods to pass the data from ViewController to ContainerView, with and without segue Here is without segue method

ViewController

 class DetailPostBookReviewVC: UIViewController {

        var postid: String!

        @IBAction func Menubutton(_ sender: Any) {

        print(postid!)

        let storyboard = UIStoryboard(name: "Main", bundle: nil)

        let vc = storyboard.instantiateViewController(withIdentifier: "MenuBookReviewVC") as! MenuBookReviewVC

        vc.favpostid = postid
 }

ContainerView

class MenuBookReviewVC: UIViewController {

    var favpostid = String()
     @IBAction func Deletepost(_ sender: Any) {
        print(favpostid)
    }
}

result: favposid has Nill Value

UPDATE this is with segue method

class DetailPostBookReviewVC: UIViewController {

     var postid: String! 

     @IBAction func Menubutton(_ sender: Any) {       
        print(postid!)

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

    if (segue.identifier == "toMenuBookReviewVC") { //"toMenuBookReviewVC" is identifier 

       let vc = segue.destination as! MenuBookReviewVC
        vc.favpostid = postid!
    }
}
Harryng
  • 13
  • 6

4 Answers4

1

Pass your data like. User prepare(for:sender:)

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if
        segue.identifier == "MyIdentifierInStorybiard", // Set that
        let controller = segue.destination as? MenuBookReviewVC {
        controller.favpostid = postid
    }
}
A. Amini
  • 521
  • 8
  • 15
  • I have tried this method but unfortunately failed. My container view is a slide up menu. When I click the Menubutton, it will come up. So I think I dont use push viewcontroller – Harryng Feb 14 '20 at 10:47
0

I think you postid is not String type so print the null value

deepak
  • 78
  • 4
  • postid is a varible String type I declared on another VC. I did print postid successfully and show the id as String – Harryng Feb 14 '20 at 12:02
0

In this way, you can't pass data for the container view. if in this way without presenting controller and push controller you can use the global variable then direct pass data and use any controller you want to use.

Example

import UIKit

class ViewController: UIViewController {
    
    var postid: String!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        postid = "23" // You change your post ID

    }
    
    @IBAction func Menubutton(_ sender: Any) {

        favpostid = postid
        
    }
        
}



var favpostid : String!

class MenuBookReviewVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        print(favpostid)
        
        
    }

}
deepak
  • 78
  • 4
-2

For Passing Data To Container View you can use this

UserDefaults.standard.set(value, forKey: "SomeKey")

after your data is used you can clear that default value.

UserDefaults.standard.set("", forKey: "SomeKey")

Vicksheet
  • 13
  • 2