Search code examples
iosswiftsegueuistoryboardsegue

viewController is presented before the segue has been passed


I have a set of buttons and I want to send their title to the next page using segue . Here is what I have done :

// in my first page i have : 
 @IBAction func btn_language_action(_ sender: UIButton) {
        let chosen_language = sender.currentTitle!
        print(chosen_language)
        let game_level = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "game_level") as! game_level_viewController
        self.present(game_level, animated: false, completion: nil)
        performSegue(withIdentifier: "GL", sender: chosen_language)

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let game_level_viewController = segue.destination as! game_level_viewController
        game_level_viewController.language = sender as? String

    }

and in the second view I have :

  @IBOutlet weak var lang: UILabel!
    var language : String?
    override func viewDidLoad() {
        super.viewDidLoad()
       setUI()
    }

    func setUI (){

        lang.text = language
        print(language )

    }

I can pass the information successfully however , however the view has already been loaded before I receive what was sent . Any idea how can I fix this ? In the console I have :

language ==>  nil
language ==>  Optional("Persian")

enter image description here


Solution

  • the problem is due to this line

    self.present(game_level, animated: false, completion: nil)
    

    why you are presenting this controller even if you have given segue to the controller

    Remove this two lines and all will work good

     let game_level = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "game_level") as! game_level_viewController
            self.present(game_level, animated: false, completion: nil)