无法将int数据从一个视图控制器传递到另一个(segue)

时间:2019-05-27 15:14:50

标签: ios swift xcode int segue

我想将一个int数据从一个视图控制器传递给另一个视图控制器。

问题是第二个视图控制器中接收到的int数据与第一个视图控制器的int数据不匹配。

视图控制器1:

import UIKit
class levelsSelector: UIViewController {
    var levelSelected: Int = 0
    var gameWanted: Int = 0

    @IBAction func level1Tapped(_ sender: Any) {
        gameWanted = 1
        performSegue(withIdentifier: "gameOn", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "gameOne" {
            let levelsSelector = segue.destination as! game
            levelsSelector.finalGame = levelSelected
            let levelsSelector2 = segue.destination as! game
            levelsSelector2.finalLevel = gameWanted
        }
    }
}

视图控制器2:

import UIKit
class game: UIViewController {
    var finalLevel: Int = 0
    var finalGame: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        print(finalLevel)
        print(finalGame)
    }
}

2 个答案:

答案 0 :(得分:0)

您用segue名字打了错字

performSegue(withIdentifier: "gameOn", sender: self)

...

if segue.identifier == "gameOne" {

这两个标识符需要匹配

答案 1 :(得分:0)

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? game {
        destination.finalGame = levelSelected 
        destination.finalLevel = gameWanted
    }

还要检查:您在故事板上的seque identifier应该与perform segue方法中的字符串匹配