无法在另一个类中获取var的值

时间:2018-07-17 22:14:20

标签: ios swift string var

我试图从另一个类中获取String var的值,但是当我在新类上使用它时,该值是空的。 我有MainViewController.swift类:

    var movieIDSelected = String()

@IBAction func tapPosterButton(_ sender: UIButton) {
    switch sender.tag
    {
    case 101: movieIDSelected = theaterMovieID[0]
    print(movieIDSelected) //The value isn't empty
        break
    }
  }

第二个MovieViewController.swift类具有:

var HomeView = ViewPop()

override func viewDidLoad() {
    super.viewDidLoad()

    let movieID = HomeView.movieIDSelected
    print(movieID) //The value is empty
}

PS:对不起,我的英语不好

1 个答案:

答案 0 :(得分:0)

使用您当前的代码,在MainVC中尝试

if let home = UIApplication.shared.keyWindow?.rootViewController as? ViewPop {
   print("home exists ",home.movieIDSelected)
}

//

但是您应该仅将1个segue链接到destinationVC,并将其链接到VC,而不是为每个按钮都进行segue链接,然后在按钮操作内实现prepareForSegue并触发performSegue来进行segue

//

@IBAction func tapPosterButton(_ sender: UIButton) {
    switch sender.tag
    {
       case 101: movieIDSelected = theaterMovieID[0]
        print(movieIDSelected) //The value isn't empty
        self.performSegue(withIdentifier: "goToNext", sender:1)

        break
    }
}

//

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

      let des = segue.destination as! MovieViewController

      des.sendedValue = self.movieIDSelected

      des.buttonNumber = sender as! Int

}

//

class MovieViewController : UIViewController {

     var sendedValue = ""

    var buttonNumber = 0 // default value won't affect 
}